10
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
# File 'lib/logical_model/has_many_keys.rb', line 10
def has_many_keys=(keys)
@has_many_keys = keys
attr_accessor *keys
keys.each do |association|
define_method association do
if instance_variable_get("@#{association}").blank?
instance_variable_set("@#{association}", [])
end
instance_variable_get("@#{association}")
end
define_method "#{association}=" do |params|
collection = []
params.each do |attr_params|
if attr_params["_type"].present?
attr_class = attr_params.delete("_type").to_s.constantize
else
attr_class = association.to_s.singularize.camelize.constantize
end
collection << attr_class.new(attr_params)
end
instance_variable_set("@#{association}", collection)
end
define_method "new_#{association.to_s.singularize}" do |attr_params|
if attr_params["_type"].present?
clazz = attr_params.delete(:_type).constantize
else
clazz = association.to_s.singularize.camelize.constantize
end
return unless clazz
temp_object = clazz.new(attr_params.merge({"#{self.json_root}_id" => self.id}))
eval(association.to_s) << temp_object
temp_object
end
define_method "#{association}_attributes=" do |key_attributes|
array = []
key_attributes.each do |attr_params|
attr_params.to_hash.symbolize_keys!
if attr_params["_type"].present?
attr_class = attr_params.delete("_type").to_s.constantize
else
attr_class = association.to_s.singularize.camelize.constantize
end
array << attr_class.new(attr_params)
end
instance_variable_set("@#{association}", array)
end
end
end
|