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
|
# File 'lib/ncore/associations.rb', line 4
def has_many(assoc, klass=nil)
assoc = assoc.to_s
klass ||= "#{module_name}::#{assoc.camelize.singularize}"
key = "#{attrib_name}_id"
class_eval <<-M1, __FILE__, __LINE__+1
def #{assoc}(params={})
return [] unless id
reload = params.delete :reload
if params.empty?
# only cache unfiltered, default api call
@attribs[:#{assoc}] = (!reload && @attribs[:#{assoc}]) || #{klass}.all({#{key}: id}, api_creds)
else
#{klass}.all(params.merge(#{key}: id), api_creds)
end
end
M1
class_eval <<-M2, __FILE__, __LINE__+1
def find_#{assoc.singularize}(aid, params={})
raise UnsavedObjectError unless id
## #{assoc}.detect{|o| o.id == aid} || raise(RecordNotFound)
# @attribs[:#{assoc}].detect{|o| o.id == aid} || #{klass}.find(aid, {#{key}: id}, api_creds)
#{klass}.find(aid, {#{key}: id}.reverse_merge(params), api_creds)
end
M2
class_eval <<-M3, __FILE__, __LINE__+1
def create_#{assoc.singularize}(params={})
raise UnsavedObjectError unless id
#{klass}.create(params.merge(#{key}: id), api_creds)
end
M3
class_eval <<-M4, __FILE__, __LINE__+1
def update_#{assoc.singularize}(aid, params={})
obj = find_#{assoc.singularize}(aid)
obj.update(params)
obj
end
M4
class_eval <<-M5, __FILE__, __LINE__+1
def create_#{assoc.singularize}!(params={})
raise UnsavedObjectError unless id
#{klass}.create!(params.merge(#{key}: id), api_creds)
end
M5
class_eval <<-M6, __FILE__, __LINE__+1
def update_#{assoc.singularize}!(aid, params={})
obj = find_#{assoc.singularize}(aid)
obj.save!(params)
end
M6
end
|