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