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
|
# File 'lib/somehow_has_relation.rb', line 10
def somehow_has(params={})
if class_variable_defined? :@@somehow_has_relation_options
class_variable_set(:@@somehow_has_relation_options, class_variable_get(:@@somehow_has_relation_options) << params)
else
class_variable_set(:@@somehow_has_relation_options, [params])
end
somehow_has_relation_options = class_variable_get(:@@somehow_has_relation_options)
times_defined = somehow_has_relation_options.count
current_options = somehow_has_relation_options[times_defined-1]
relation = current_options[:one] || current_options[:many]
default_method_name = "related_#{relation}"
related = current_options[:as] || default_method_name
define_method(related) do
found = somehow_found_or_recur relation, current_options[:if], current_options
if current_options.has_key?(:one)
found.flatten.compact.first rescue found
elsif current_options.has_key?(:many)
found.flatten.compact rescue []
end
end
end
|