/
associations.rb
90 lines (69 loc) · 2.44 KB
/
associations.rb
1
2
3
4
5
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
module ActiveHash
module Associations
module ActiveRecordExtensions
def belongs_to_active_hash(association_id, options = {})
options = {
:class_name => association_id.to_s.camelize,
:foreign_key => association_id.to_s.foreign_key
}.merge(options)
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
create_reflection(
:belongs_to,
association_id.to_sym,
options,
options[:class_name].constantize
)
end
end
def self.included(base)
base.extend Methods
end
module Methods
def has_many(association_id, options = {})
define_method(association_id) do
options = {
:class_name => association_id.to_s.classify,
:foreign_key => self.class.to_s.foreign_key
}.merge(options)
klass = options[:class_name].constantize
if klass.respond_to?(:scoped)
klass.scoped(:conditions => {options[:foreign_key] => id})
else
klass.send("find_all_by_#{options[:foreign_key]}", id)
end
end
end
def has_one(association_id, options = {})
define_method(association_id) do
options = {
:class_name => association_id.to_s.classify,
:foreign_key => self.class.to_s.foreign_key
}.merge(options)
scope = options[:class_name].constantize
if scope.respond_to?(:scoped) && options[:conditions]
scope = scope.scoped(:conditions => options[:conditions])
end
scope.send("find_by_#{options[:foreign_key]}", id)
end
end
def belongs_to(association_id, options = {})
options = {
:class_name => association_id.to_s.classify,
:foreign_key => association_id.to_s.foreign_key
}.merge(options)
field options[:foreign_key].to_sym
define_method(association_id) do
options[:class_name].constantize.find_by_id(send(options[:foreign_key]))
end
define_method("#{association_id}=") do |new_value|
attributes[options[:foreign_key].to_sym] = new_value ? new_value.id : nil
end
end
end
end
end