7
8
9
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
|
# File 'lib/consumerable/associations/belongs_to.rb', line 7
def belongs_to(association_name, options = {})
foreign_key = options[:foreign_key] || :"#{association_name}_id"
class_eval do
attribute foreign_key, String
end
(class << self; self; end).instance_eval do
define_method "_for_#{association_name}" do |id|
init_collection Consumerable::Connection.
get(list_path.gsub(/:#{association_name}_id/, id))
end
end
define_method association_name do
instance_variable_get(:"@#{association_name}") ||
if self.send(foreign_key)
options[:class_name].constantize.
find(self.send(foreign_key)).tap do |parent|
self.send("#{association_name}=", object)
end
else
nil
end
end
define_method "#{association_name}=" do |associated_object|
instance_variable_set(:"@#{association_name}", associated_object)
id = associated_object ? associated_object.id : nil
self.send "#{foreign_key}=", id
end
end
|