Skip to content

Instantly share code, notes, and snippets.

@shostakovich
Created November 30, 2012 12:13
Show Gist options
  • Save shostakovich/4175440 to your computer and use it in GitHub Desktop.
Save shostakovich/4175440 to your computer and use it in GitHub Desktop.
Reading of OpenStruct
def [](name)
@table[name.to_sym]
end
def []=(name, value)
modifiable[new_ostruct_member(name)] = value
end
def initialize(hash=nil)
@table = {}
if hash
hash.each_pair do |k, v|
k = k.to_sym
@table[k] = v
new_ostruct_member(k)
end
end
def initialize_copy(orig)
super
@table = @table.dup
@table.each_key{|key| new_ostruct_member(key)}
end
def method_missing(mid, *args) # :nodoc:
mname = mid.id2name
len = args.length
if mname.chomp!('=') && mid != :[]=
if len != 1
raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1)
end
modifiable[new_ostruct_member(mname)] = args[0]
elsif len == 0 && mid != :[]
@table[mid]
else
raise NoMethodError, "undefined method `#{mid}' for #{self}", caller(1)
end
end
def modifiable
begin
@modifiable = true
rescue
raise TypeError, "can't modify frozen #{self.class}", caller(3)
end
@table
end
protected :modifiable
def new_ostruct_member(name)
name = name.to_sym
unless respond_to?(name)
define_singleton_method(name) { @table[name] }
define_singleton_method("#{name}=") { |x| modifiable[name] = x }
end
name
end
protected :new_ostruct_member
InspectKey = :__inspect_key__ # :nodoc:
def inspect
str = "#<#{self.class}"
ids = (Thread.current[InspectKey] ||= [])
if ids.include?(object_id)
return str << ' ...>'
end
ids << object_id
begin
first = true
for k,v in @table
str << "," unless first
first = false
str << " #{k}=#{v.inspect}"
end
return str << '>'
ensure
ids.pop
end
end
alias :to_s :inspect
def marshal_dump
@table
end
def marshal_load(x)
@table = x
@table.each_key{|key| new_ostruct_member(key)}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment