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
|
# File 'lib/opto/model/association/has_many/declaration.rb', line 13
def has_many(relation, klass, options = {})
if relations.include?(relation)
raise RuntimeError, "Duplicate has_many relation '#{relation}'"
end
relations << relation
define_method relation do
if instance_variable_defined?("@#{relation}")
instance_variable_get("@#{relation}")
else
instance_variable_set("@#{relation}", Proxy.new(self, klass, relation, options))
end
end
define_method "#{relation}=" do |args|
if args.kind_of?(Array)
self.send(relation).clear
args.each do |arg|
if arg.kind_of?(klass)
self.send(relation).push(arg)
elsif arg.kind_of?(Hash)
self.send(relation).new(arg)
else
raise TypeError, "Expected an instance of #{klass} or Hash"
end
end
self.send(relation).members
elsif args.kind_of?(Hash)
self.send(relation).clear
args.each do |k,v|
if v.kind_of?(Hash)
self.send(relation).new(k => v)
else
raise TypeError, "Expected an instance of Hash"
end
end
self.send(relation).members
elsif args.nil?
self.send(relation).clear
else
raise TypeError, "Expected an instance of Array"
end
end
end
|