Overriding getter of OpenStruct in order to print it as a Hash

1.6k Views Asked by At

GOAL: Values of an OpenStruct object should be printed as a hash rather than an object

POSSIBLE SOLUTION: Override getter of the OpenStruct class

MyOpenStruct overrides new, to_h and [] of OpenStruct.

class MyOpenStruct < OpenStruct
    def initialize(object=nil)
        @table = {}
        @hash_table = {}

        if object
            object.each do |k,v|
                if v.is_a?(Array)
                    other = Array.new()
                    v.each { |e| other.push(self.class.new(entry)) }
                    v = other
                end
                @table[k.to_sym] = (v.is_a?(Hash) ? self.class.new(v) : v)
                @hash_table[k.to_sym] = v
                new_ostruct_member(k)
            end
        end
    end

    def [](val)
        @hash_table[val.to_sym]
    end
end

But overriding [] is not making any difference. E.g.

irb(main):007:0> temp = MyOpenStruct.new({"name"=>"first", "place"=>{"animal"=>"thing"}})
=> #<MyOpenStruct name="first", place=#<MyOpenStruct animal="thing">>
irb(main):008:0> temp.name
=> "first"
irb(main):009:0> temp.place
=> #<MyOpenStruct animal="thing">
irb(main):010:0> temp["place"]
=> {"animal"=>"thing"}
irb(main):011:0> temp[:place]
=> {"animal"=>"thing"}
irb(main):012:0> temp
=> #<MyOpenStruct name="first", place=#<MyOpenStruct animal="thing">>

Only when I access the keys using [] a hash is returned!!

How can I correct this??

2

There are 2 best solutions below

1
Doguita On

I don't believe create a nested OpenStruct makes sense if you are returning it as a Hash. That's the way OpenStruct works:

require 'ostruct'
struct = OpenStruct.new(name: 'first', place: { animal: 'thing' })
struct.place
# => {:animal=>"thing"}
struct.place[:animal]
# => "thing"
struct.place.animal
# => NoMethodError: undefined method `animal' for {:animal=>"thing"}:Hash

So, if you want to use the dot notation to get struct.place.animal, you need to create nested OpenStruct objects like you did. But, as I said, you don't need to override the [] method. Using your class without override the [] I get this:

struct = MyOpenStruct.new(name: 'first', place: { animal: 'thing' })
# => #<MyOpenStruct name="first", place=#<MyOpenStruct animal="thing">> 
struct.place
# => #<MyOpenStruct animal="thing"> 
struct.place.animal
# => "thing" 

Anyway, if you really want to make the dot notation work as you asked, you can override the new_ostruct_member method, which is used internally to create dynamic attributes when setting the OpenStruct object. You can try something like this, but I don't recommend:

class MyOpenStruct < OpenStruct
  def initialize(object=nil)
    @table = {}
    @hash_table = {}

    if object
      object.each do |k,v|
        if v.is_a?(Array)
          other = Array.new()
          v.each { |e| other.push(self.class.new(entry)) }
          v = other
        end
        @table[k.to_sym] = (v.is_a?(Hash) ? self.class.new(v) : v)
        @hash_table[k.to_sym] = v
        new_ostruct_member(k)
      end
    end
  end

  def [](val)
    @hash_table[val.to_sym]
  end

  protected

  def new_ostruct_member(name)
    name = name.to_sym
    unless respond_to?(name)
      # use the overrided `[]` method, to return a hash
      define_singleton_method(name) { self[name] }
      define_singleton_method("#{name}=") { |x| modifiable[name] = x }
    end
    name
  end
end

struct = MyOpenStruct.new(name: 'first', place: { animal: 'thing' })
# => #<MyOpenStruct name="first", place=#<MyOpenStruct animal="thing">> 
struct.place
# => {:animal=>"thing"} 
struct.place[:animal]
# => "thing" 
4
Jordan Running On

@Doguita's answer is correct in all respects. I just wanted to answer your question "If that's not possible then can I print a hash of the whole object temp?" Yes, you can. You just need to override to_h to recursively walk your keys and values and convert instances of MyOpenStruct to a Hash:

def to_h
  @table.each_with_object({}) do |(key, val), table|
    table[key] = to_h_convert(val)
  end
end

private
def to_h_convert(val)
  case val
  when self.class
    val.to_h
  when Hash
    val.each_with_object({}) do |(key, val), hsh|
      hsh[key] = to_h_convert(val)
    end
  when Array
    val.map {|item| to_h_convert(item) }
  else
    val
  end
end