Construct nested OpenStruct object

2.9k Views Asked by At

I have to mimic a Google API response and create a 2-level deep data structure that is traversable by . like this:

=> user.names.first_name

Bob

Is there any smarter/better way than this:

 user = OpenStruct.new(names: OpenStruct.new(first_name: 'Bob'))
1

There are 1 best solutions below

3
nerding_it On BEST ANSWER

This method is rude method but works,

require 'ostruct'
require 'json'
# Data in hash
data = {"names" => {"first_name" => "Bob"}}
result = JSON.parse(data.to_json, object_class: OpenStruct)

And another method is adding method to Hash class itself,

class Hash
  def to_openstruct
    JSON.parse to_json, object_class: OpenStruct
  end
end

Using above method you can convert your hash to openstruct

data = {"names" => {"first_name" => "Bob"}}
data.to_openstruct