Class: FormObj::Struct
- Inherits:
-
Object
show all
- Defined in:
- lib/form_obj/struct.rb,
lib/form_obj/struct/array.rb,
lib/form_obj/struct/attribute.rb,
lib/form_obj/struct/attributes.rb
Direct Known Subclasses
Form
Defined Under Namespace
Classes: Array, Attribute, Attributes
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(*args) ⇒ Struct
Returns a new instance of Struct.
62
63
64
65
|
# File 'lib/form_obj/struct.rb', line 62
def initialize(*args)
super()
update_attributes(*args) if args.size > 0 && args[0]
end
|
Class Method Details
.array_class ⇒ Object
19
20
21
|
# File 'lib/form_obj/struct.rb', line 19
def array_class
Array
end
|
.attribute(name, opts = {}, &block) ⇒ Object
31
32
33
34
35
36
37
|
# File 'lib/form_obj/struct.rb', line 31
def attribute(name, opts = {}, &block)
attr = attribute_class.new(name, opts.merge(parent: self), &block)
self._attributes = _attributes.add(attr)
_define_attribute_getter(attr)
_define_attribute_setter(attr)
self
end
|
.attribute_class ⇒ Object
27
28
29
|
# File 'lib/form_obj/struct.rb', line 27
def attribute_class
Attribute
end
|
.attributes ⇒ Object
39
40
41
|
# File 'lib/form_obj/struct.rb', line 39
def attributes
self._attributes.map(&:name)
end
|
.inspect ⇒ Object
43
44
45
|
# File 'lib/form_obj/struct.rb', line 43
def inspect
"#{name}#{attributes.size > 0 ? "(#{attributes.join(', ')})" : ''}"
end
|
.nested_class ⇒ Object
23
24
25
|
# File 'lib/form_obj/struct.rb', line 23
def nested_class
::FormObj::Struct
end
|
Instance Method Details
#inspect ⇒ Object
97
98
99
|
# File 'lib/form_obj/struct.rb', line 97
def inspect
"#<#{self.class.name} #{self.class._attributes.map { |attribute| "#{attribute.name}: #{read_attribute(attribute).inspect}"}.join(', ')}>"
end
|
#primary_key ⇒ Object
67
68
69
|
# File 'lib/form_obj/struct.rb', line 67
def primary_key
send(self.class.primary_key)
end
|
#primary_key=(val) ⇒ Object
71
72
73
|
# File 'lib/form_obj/struct.rb', line 71
def primary_key=(val)
send("#{self.class.primary_key}=", val)
end
|
#to_hash ⇒ Object
93
94
95
|
# File 'lib/form_obj/struct.rb', line 93
def to_hash
Hash[self.class._attributes.map { |attribute| [attribute.name, attribute.subform? ? read_attribute(attribute).to_hash : read_attribute(attribute)] }]
end
|
#update_attributes(new_attrs, raise_if_not_found: true) ⇒ Object
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
# File 'lib/form_obj/struct.rb', line 75
def update_attributes(new_attrs, raise_if_not_found: true)
new_attrs = HashWithIndifferentAccess.new(new_attrs) unless new_attrs.is_a? HashWithIndifferentAccess
new_attrs.each_pair do |new_attr, new_val|
attr = self.class._attributes.find(new_attr)
if attr.nil?
raise UnknownAttributeError.new(new_attr) if raise_if_not_found
else
if attr.subform?
self.send(new_attr).update_attributes(new_val, raise_if_not_found: raise_if_not_found)
else
update_attribute(attr, new_val)
end
end
end
self
end
|