Module | OpenStructable |
In: |
lib/more/facets/ostructable.rb
|
OpensStructable is a mixin module which can provide OpenStruct behavior to any class or object. OpenStructable allows extention of data objects with arbitrary attributes.
require 'ostructable' class Record include OpenStructable end record = Record.new record.name = "John Smith" record.age = 70 record.pension = 300 puts record.name # -> "John Smith" puts record.address # -> nil
# File lib/more/facets/ostructable.rb, line 61 61: def initialize(hash=nil) 62: @__table__ = {} 63: if hash 64: for k,v in hash 65: @__table__[k.to_sym] = v 66: new_ostruct_member(k) 67: end 68: end 69: end
Compare this object and other for equality.
# File lib/more/facets/ostructable.rb, line 154 154: def ==(other) 155: return false unless(other.kind_of?(OpenStruct)) 156: return @__table__ == other.table 157: end
Remove the named field from the object.
# File lib/more/facets/ostructable.rb, line 132 132: def delete_field(name) 133: @__table__ ||= {} 134: @__table__.delete name.to_sym 135: end
duplicate an OpenStruct object members.
# File lib/more/facets/ostructable.rb, line 72 72: def initialize_copy(orig) 73: super 74: @__table__ = @__table__.dup 75: end
Returns a string containing a detailed summary of the keys and values.
# File lib/more/facets/ostructable.rb, line 140 140: def inspect 141: str = "<#{self.class}" 142: for k,v in (@__table__ ||= {}) 143: str << " #{k}=#{v.inspect}" 144: end 145: str << ">" 146: end
# File lib/more/facets/ostructable.rb, line 80 80: def marshal_load(x) 81: @table = x 82: @table.each_key{|key| new_ostruct_member(key)} 83: end
# File lib/more/facets/ostructable.rb, line 85 85: def new_ostruct_member(name) 86: unless self.respond_to?(name) 87: self.instance_eval %{ 88: def #{name}; @__table__[:#{name}]; end 89: def #{name}=(x); @__table__[:#{name}] = x; end 90: } 91: end 92: end