Class: MongoThing::NestedOpenStruct
- Inherits:
-
OpenStruct
- Object
- OpenStruct
- MongoThing::NestedOpenStruct
show all
- Defined in:
- lib/mongo_thing/nested_ostruct.rb
Instance Method Summary
collapse
Constructor Details
Returns a new instance of NestedOpenStruct.
7
8
9
10
11
12
13
14
15
16
|
# File 'lib/mongo_thing/nested_ostruct.rb', line 7
def initialize(hash=nil)
@table = {}
if hash
for k,v in hash
v = convert_value_to_nested_open_struct(v)
@table[k.to_sym] = v
new_ostruct_member(k)
end
end
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(mid, *args) ⇒ Object
18
19
20
21
22
23
24
|
# File 'lib/mongo_thing/nested_ostruct.rb', line 18
def method_missing(mid, *args) mname = mid.id2name
if mname[-1..-1] == "=" && args[0]
args[0] = convert_value_to_nested_open_struct(args[0])
end
super
end
|
Instance Method Details
#convert_value_to_nested_open_struct(value) ⇒ Object
26
27
28
29
30
31
32
33
34
35
|
# File 'lib/mongo_thing/nested_ostruct.rb', line 26
def convert_value_to_nested_open_struct(value)
case value
when Hash
NestedOpenStruct.new(value)
when Array
value.collect{|nv| nv.is_a?(Hash) ? NestedOpenStruct.new(nv) : nv}
else
value
end
end
|
#marshal_dump ⇒ Object
52
53
54
55
56
57
58
59
60
61
62
63
|
# File 'lib/mongo_thing/nested_ostruct.rb', line 52
def marshal_dump
@table.collect do |k,v|
n = if v.is_a?(NestedOpenStruct)
v.marshal_dump
elsif v.is_a?(Array)
v.collect{|a| a.is_a?(NestedOpenStruct) ? a.marshal_dump : a}
else
v
end
[k,n]
end.inject({}){|h,v|h[v[0]] = v[1]; h}
end
|
#marshal_load(x) ⇒ Object
65
66
67
68
|
# File 'lib/mongo_thing/nested_ostruct.rb', line 65
def marshal_load(x)
@table = x
@table.each_key{|key| new_ostruct_member(key)}
end
|
#new_ostruct_member(name) ⇒ Object
41
42
43
44
45
46
47
48
49
50
|
# File 'lib/mongo_thing/nested_ostruct.rb', line 41
def new_ostruct_member(name)
name = name.to_sym
unless self.respond_to?(name)
self.class.class_eval do
define_method(name) { @table[name] }
define_method("#{name}=") { |x| modifiable[name] = convert_value_to_nested_open_struct(x) }
end
end
name
end
|
#to_hash ⇒ Object
37
38
39
|
# File 'lib/mongo_thing/nested_ostruct.rb', line 37
def to_hash
marshal_dump
end
|