| Class | OpenStruct |
| In: |
lib/ostruct.rb
|
| Parent: | Object |
OpenStruct allows you to create data objects and set arbitrary attributes. For example:
require 'ostruct' record = OpenStruct.new record.name = "John Smith" record.age = 70 record.pension = 300 puts record.name # -> "John Smith" puts record.address # -> nil
It is like a hash with a different way to access the data. In fact, it is implemented with a hash, and you can initialize it with one.
hash = { "country" => "Australia", :population => 20_000_000 }
data = OpenStruct.new(hash)
p data # -> <OpenStruct country="Australia" population=20000000>
Create a new OpenStruct object. The optional hash, if given, will generate attributes and values. For example.
require 'ostruct'
hash = { "country" => "Australia", :population => 20_000_000 }
data = OpenStruct.new(hash)
p data # -> <OpenStruct country="Australia" population=20000000>
By default, the resulting OpenStruct object will have no attributes.
# File lib/ostruct.rb, line 46
46: def initialize(hash=nil)
47: @table = {}
48: if hash
49: for k,v in hash
50: @table[k.to_sym] = v
51: new_ostruct_member(k)
52: end
53: end
54: end
Compare this object and other for equality.
# File lib/ostruct.rb, line 142
142: def ==(other)
143: return false unless(other.kind_of?(OpenStruct))
144: return @table == other.table
145: end
Remove the named field from the object.
# File lib/ostruct.rb, line 102
102: def delete_field(name)
103: @table.delete name.to_sym
104: end
Duplicate an OpenStruct object members.
# File lib/ostruct.rb, line 57
57: def initialize_copy(orig)
58: super
59: @table = @table.dup
60: end
Returns a string containing a detailed summary of the keys and values.
# File lib/ostruct.rb, line 111
111: def inspect
112: str = "#<#{self.class}"
113:
114: Thread.current[InspectKey] ||= []
115: if Thread.current[InspectKey].include?(self) then
116: str << " ..."
117: else
118: first = true
119: for k,v in @table
120: str << "," unless first
121: first = false
122:
123: Thread.current[InspectKey] << v
124: begin
125: str << " #{k}=#{v.inspect}"
126: ensure
127: Thread.current[InspectKey].pop
128: end
129: end
130: end
131:
132: str << ">"
133: end
# File lib/ostruct.rb, line 65
65: def marshal_load(x)
66: @table = x
67: @table.each_key{|key| new_ostruct_member(key)}
68: end
# File lib/ostruct.rb, line 70
70: def new_ostruct_member(name)
71: name = name.to_sym
72: unless self.respond_to?(name)
73: meta = class << self; self; end
74: meta.send(:define_method, name) { @table[name] }
75: meta.send(:define_method, "#{name}=""#{name}=") { |x| @table[name] = x }
76: end
77: end