Class: EmbedsMany::Child
- Inherits:
-
Object
show all
- Extended by:
- ActiveModel::Validations::ClassMethods
- Includes:
- ActiveModel::Dirty, ActiveModel::Validations
- Defined in:
- lib/embeds_many/child.rb
Defined Under Namespace
Classes: UniquenessValidator
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(attrs = {}) ⇒ Child
Returns a new instance of Child.
36
37
38
39
40
41
42
43
44
45
46
|
# File 'lib/embeds_many/child.rb', line 36
def initialize(attrs={})
@attributes = ActiveSupport::HashWithIndifferentAccess.new
attrs.each do |name, value|
if respond_to? "#{name}="
send("#{name}=", value)
else
@attributes[name] = value
end
end
end
|
Instance Attribute Details
#parent ⇒ Object
Returns the value of attribute parent.
20
21
22
|
# File 'lib/embeds_many/child.rb', line 20
def parent
@parent
end
|
Class Method Details
.embedded_fields(*fields) ⇒ Object
8
9
10
11
12
13
14
15
16
17
18
|
# File 'lib/embeds_many/child.rb', line 8
def self.embedded_fields(*fields)
fields.each do |field_name|
define_method(field_name) do
@attributes[field_name]
end
define_method("#{field_name}=") do |val|
@attributes[field_name] = val
end
end
end
|
.model_name ⇒ Object
validation requires model name
32
33
34
|
# File 'lib/embeds_many/child.rb', line 32
def self.model_name
ActiveModel::Name.new(self, nil, self.name || @field_name.to_s.classify)
end
|
Instance Method Details
#before_parent_save ⇒ Object
96
97
98
99
100
101
102
103
104
|
# File 'lib/embeds_many/child.rb', line 96
def before_parent_save
return if @operation_pending or !self.valid?
if new_record?
fill_parent_field_new_record!
else
fill_parent_field_existing_record!
end
end
|
#destroy ⇒ Object
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
# File 'lib/embeds_many/child.rb', line 62
def destroy
parent.send "#{field_name}_will_change!"
parent.read_attribute(field_name).delete_if {|t| t['id'] == self.id}
@operation_pending = true
if parent.update(field_name => parent.read_attribute(field_name))
parent.send(field_name).child_destroyed(self)
true
else
parent.send "#{field_name}=", parent.send("#{field_name}_was")
false
end
ensure
@operation_pending = false
end
|
#exists_in_parent?(&block) ⇒ Boolean
92
93
94
|
# File 'lib/embeds_many/child.rb', line 92
def exists_in_parent?(&block)
parent.read_attribute(field_name).any? &block
end
|
#new_record? ⇒ Boolean
88
89
90
|
# File 'lib/embeds_many/child.rb', line 88
def new_record?
self.id.nil?
end
|
#save ⇒ Object
48
49
50
51
52
53
54
55
56
57
58
59
60
|
# File 'lib/embeds_many/child.rb', line 48
def save
return false unless self.valid?
@operation_pending = true
if new_record?
save_new_record!
else
save_existing_record!
end
ensure
@operation_pending = false
end
|
#update(attrs) ⇒ Object
82
83
84
85
86
|
# File 'lib/embeds_many/child.rb', line 82
def update(attrs)
@attributes.update(attrs)
save
end
|