11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
# File 'lib/has_many_callbacks.rb', line 11
def build
association = super
hook_callback = lambda do |callback_name|
callback_option = association.options[callback_name]
if callback_option.is_a?(Symbol)
callback_code = "target.send(:#{callback_option}, obj)"
else
callback_code = "callback_option[target, obj]"
end
if association.inverse_of.macro == :has_many
target_callback_iteration_code = "associated_obj.each { |target| #{callback_code} }"
else
target_callback_iteration_code = "target = associated_obj; #{callback_code}"
end
code = %{
#{callback_name} do |obj|
association = obj.class.reflect_on_association(:#{association.inverse_of.name})
inverse_association = association.klass.reflect_on_association(:#{association.name})
callback_option = inverse_association.options[:#{callback_name}]
associated_obj = obj.send(association.name)
if associated_obj.present?
#{target_callback_iteration_code}
end
end
}
association.klass.instance_eval code
end
HAS_MANY_CALLBACKS.each do |callback|
if options[callback].present?
hook_callback[callback]
end
end
association
end
|