| 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 145
145: def ==(other)
146: return false unless(other.kind_of?(OpenStruct))
147: return @table == other.table
148: end
Remove the named field from the object.
# File lib/ostruct.rb, line 107
107: def delete_field(name)
108: @table.delete name.to_sym
109: 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 116
116: def inspect
117: str = "#<#{self.class}"
118:
119: ids = (Thread.current[InspectKey] ||= [])
120: if ids.include?(object_id)
121: return str << ' ...>'
122: end
123:
124: ids << object_id
125: begin
126: first = true
127: for k,v in @table
128: str << "," unless first
129: first = false
130: str << " #{k}=#{v.inspect}"
131: end
132: return str << '>'
133: ensure
134: ids.pop
135: end
136: 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 78
78: def new_ostruct_member(name)
79: name = name.to_sym
80: unless self.respond_to?(name)
81: class << self; self; end.class_eval do
82: define_method(name) { @table[name] }
83: define_method("#{name}=") { |x| modifiable[name] = x }
84: end
85: end
86: name
87: end