5

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'))
Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232
  • Does this answer your question? [Convert Hash to OpenStruct recursively](https://stackoverflow.com/questions/42519557/convert-hash-to-openstruct-recursively) – Jon Schneider Oct 04 '22 at 15:50

1 Answers1

10

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
nerding_it
  • 704
  • 7
  • 17