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/accepts_flattened_values/mixin.rb', line 13
def accepts_flattened_values_for(*attr_names)
options = { :separator => ',', :value => :value }
options.update(attr_names.)
options.assert_valid_keys(:separator, :value)
attr_names.each do |association_name|
if reflection = reflect_on_association(association_name)
reflection.options[:autosave] = true
add_autosave_association_callbacks(reflection)
flattened_values_options[association_name.to_sym] = options
flattened_values_klasses[association_name.to_sym] = reflection.klass
unless reflection.collection?
raise ArugmentError, "Assocation `#{association_name}' must be a collection."
end
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
if method_defined?(:#{association_name}_values)
remove_method(:#{association_name}_values)
end
def #{association_name}_values
get_flattened_values_for_association(:#{association_name})
end
if method_defined?(:#{association_name}_values=)
remove_method(:#{association_name}_values=)
end
def #{association_name}_values=(values)
assign_flattened_values_for_association(:#{association_name}, values)
end
RUBY_EVAL
else
raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
end
end
end
|