Given I have this hash:
h = { a: 'a', b: 'b', c: { d: 'd', e: 'e'} }
And I convert to OpenStruct:
o = OpenStruct.new(h) => #<OpenStruct a="a", b="b", c={:d=>"d", :e=>"e"}> o.a => "a" o.b => "b" o.c => {:d=>"d", :e=>"e"} 2.1.2 :006 > o.c.d NoMethodError: undefined method `d' for {:d=>"d", :e=>"e"}:Hash
I want all the nested keys to be methods as well. So I can access d
as such:
o.c.d => "d"
How can I achieve this?
You can monkey-patch the Hash
class
class Hash def to_o JSON.parse to_json, object_class: OpenStruct end end
then you can say
h = { a: 'a', b: 'b', c: { d: 'd', e: 'e'} } o = h.to_o o.c.d # => 'd'
See Convert a complex nested hash to an object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With