OpenStructable

OpensStructable is a mixin module which can provide OpenStruct behavior to any class or object. OpenStructable allows extention of data objects with arbitrary attributes.

Usage

  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

Author(s)

Public Class Methods

new(hash=nil) click to toggle source
    # 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

Public Instance Methods

==(other) click to toggle source

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
delete_field(name) click to toggle source

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
initialize_copy(orig) click to toggle source

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
inspect() click to toggle source

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
marshal_dump() click to toggle source
    # File lib/more/facets/ostructable.rb, line 77
77:   def marshal_dump
78:     @table
79:   end
marshal_load(x) click to toggle source
    # 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
new_ostruct_member(name) click to toggle source
    # 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
update(hash) click to toggle source

Generate additional attributes and values.

     # File lib/more/facets/ostructable.rb, line 97
 97:   def update(hash)
 98:     @__table__ ||= {}
 99:     if hash
100:       for k,v in hash
101:         @__table__[k.to_sym] = v
102:         new_ostruct_member(k)
103:       end
104:     end
105:   end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.