Search code examples
rubyopenstruct

Construct nested OpenStruct object


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'))

Solution

  • 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