Class: ClassyStruct::ClassyStructClass
- Inherits:
-
Object
- Object
- ClassyStruct::ClassyStructClass
show all
- Defined in:
- lib/classy_struct.rb
Class Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
Returns a new instance of ClassyStructClass.
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
# File 'lib/classy_struct.rb', line 10
def initialize(hash=nil)
if hash
hash.each_pair do |k,v|
k = self.class.method_mapper.call(k.to_s) if self.class.method_mapper
if v.is_a?(Hash)
v = self.class.node_class(k).new(v)
elsif v.is_a?(Array)
v = self.class.map_array(k, v)
end
send("#{k}=", v)
end
end
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args) ⇒ Object
77
78
79
80
81
82
83
84
85
|
# File 'lib/classy_struct.rb', line 77
def method_missing(name, *args)
base = (name.to_s =~ /=$/) ? name.to_s[0..-2] : name
self.class.class_eval "attr_accessor :#{base}"
self.class.attr_names << base.to_sym
send(name, *args)
end
|
Class Attribute Details
.attr_names ⇒ Object
Returns the value of attribute attr_names.
28
29
30
|
# File 'lib/classy_struct.rb', line 28
def attr_names
@attr_names
end
|
.method_mapper ⇒ Object
Returns the value of attribute method_mapper.
27
28
29
|
# File 'lib/classy_struct.rb', line 27
def method_mapper
@method_mapper
end
|
Class Method Details
.map_array(key, ary) ⇒ Object
35
36
37
38
39
40
41
42
43
44
|
# File 'lib/classy_struct.rb', line 35
def map_array(key, ary)
ary.map do |e|
case e
when Hash
node_class(key).new(e)
else
e
end
end
end
|
.node_class(name) ⇒ Object
30
31
32
33
|
# File 'lib/classy_struct.rb', line 30
def node_class(name)
@__node_classes ||= {}
@__node_classes[name.to_sym] ||= ClassyStruct.new(&method_mapper)
end
|
Instance Method Details
#_attrs ⇒ Object
47
48
49
50
51
52
|
# File 'lib/classy_struct.rb', line 47
def _attrs
self.class.attr_names.inject({}) do |retval, attr_name|
retval[attr_name] = send(attr_name)
retval
end
end
|
#inspect ⇒ Object
54
55
56
|
# File 'lib/classy_struct.rb', line 54
def inspect
to_hash.inspect
end
|
#new_child(key) ⇒ Object
73
74
75
|
# File 'lib/classy_struct.rb', line 73
def new_child(key)
self.send("#{key}=", self.class.node_class(key).new)
end
|
#to_hash ⇒ Object
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
# File 'lib/classy_struct.rb', line 58
def to_hash
retval = _attrs
retval.each_pair do |key,val|
case val
when ClassyStruct::ClassyStructClass
retval[key] = val.to_hash
when Array
retval[key] = val.map{|e| e.is_a?(ClassyStruct::ClassyStructClass) ? e.to_hash : e}
end
end
retval
end
|