Unable to access the id field of an OpenStruct instance

I have code in Ruby as shown below: Ruby version: 1.8.7

hash = OpenStruct.new(:id=>123, :name=>'wenbo')
puts "#{hash.id} -- #{hash.name}"

D:/workspace/wmch/rubytest/lib/variable.rb:17: warning: Object#id will be deprecated; use Object#object_id
27556896 -- wenbo

Can someone help me on how to get the id field value for 123?

+3
source share
2 answers

Looks like an OpenStruct bug / restriction in section 1.8.7, where there is no BlankSlate object called by the implementation, which it uses method_missingto decide whether this is a special property or not.

Here, a custom class, similar to OpenStruct, does what you ask for in section 1.8.7; Feel free to expand it and make it more multifunctional.

class MemoStruct
  def initialize( h=nil )
    h.each{ |k,v| add_field(k,v) } if h
  end
  def add_field( name, value=nil )
    inst = :"@#{name}"
    (class << self; self; end).class_eval do
      define_method(name){ instance_variable_get inst }
      define_method("#{name}="){ |v| instance_variable_set inst,v }
    end
    instance_variable_set(inst,value)
  end
  def []=( name, value )
    add_field(name,value)
  end
end

hash = MemoStruct.new :id=>123, :name=>"Jim"
p hash.id
#=> 123

hash["new_field"] = "stuff"
p hash.new_field
#=> stuff
+2
source

This blog post will be answered with this simple line of code.

OpenStruct.__send__(:define_method, :id) { @table[:id] }

: id OpenStruct : object_id

+4

Source: https://habr.com/ru/post/1790268/


All Articles