6
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
39
40
41
42
43
44
45
46
47
48
49
|
# File 'lib/associations/associations.rb', line 6
def belongs_to_active_hash(association_id, options = {})
options = {
:class_name => association_id.to_s.camelize,
:foreign_key => association_id.to_s.foreign_key,
:shortcuts => []
}.merge(options)
options[:shortcuts] = [options[:shortcuts]] unless options[:shortcuts].kind_of?(Array)
define_method(association_id) do
options[:class_name].constantize.find_by_id(send(options[:foreign_key]))
end
define_method("#{association_id}=") do |new_value|
send "#{options[:foreign_key]}=", new_value ? new_value.id : nil
end
options[:shortcuts].each do |shortcut|
define_method("#{association_id}_#{shortcut}") do
send(association_id).try(shortcut)
end
define_method("#{association_id}_#{shortcut}=") do |new_value|
send "#{association_id}=", new_value ? options[:class_name].constantize.send("find_by_#{shortcut}", new_value) : nil
end
end
method = ActiveRecord::Base.method(:create_reflection)
if method.respond_to?(:parameters) && method.parameters.length == 5
create_reflection(
:belongs_to,
association_id.to_sym,
nil,
options,
self
)
else
create_reflection(
:belongs_to,
association_id.to_sym,
options,
options[:class_name].constantize
)
end
end
|