Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Hash to OpenStruct recursively

Tags:

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?

like image 736
Daniel Viglione Avatar asked Feb 28 '17 22:02

Daniel Viglione


1 Answers

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.

like image 57
Cruz Nunez Avatar answered Sep 23 '22 07:09

Cruz Nunez