Module: ActsAsArray::ClassMethods
- Defined in:
- lib/acts_as_array.rb
Instance Method Summary collapse
-
#acts_as_array(params = {}) ⇒ Object
acts_as_array :has_many_field => => Class, :field => :name.
Instance Method Details
#acts_as_array(params = {}) ⇒ Object
acts_as_array :has_many_field => => Class, :field => :name
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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/acts_as_array.rb', line 10 def acts_as_array(params = {}) params.each do |field, opts| opts[:class] ||= field.to_s.singularize.capitalize.constantize end self.class_eval do params.each do |field, opts| # Setter with an array mapper # # Example: # # mails = ['[email protected]', '[email protected]'] # # instead of # # mails = [Mail.new(name: '[email protected]'), Mail.new(name: '[email protected]')] unless method_defined?("#{field}_with_arraymap=") define_method("#{field}_with_arraymap=") do |raw_array| obj_array = __send__("make_#{field}", raw_array) __send__("#{field}_without_arraymap=", obj_array) end define_method("#{field}=") {|*args| } unless method_defined?("#{field}=") alias_method("#{field}_without_arraymap=", "#{field}=") alias_method("#{field}=", "#{field}_with_arraymap=") end # Getter with an array mapper # # Example: # # mails #=> ['[email protected]', '[email protected]'] # # instead of # # mails #=> [Mail.new(name: '[email protected]'), Mail.new(name: '[email protected]')] unless method_defined?("#{field}_with_arraymap") define_method("#{field}_with_arraymap") do obj_array = __send__("#{field}_without_arraymap") obj_array.map {|obj| obj.__send__(opts[:field]) } end define_method("#{field}") { } unless method_defined?("#{field}") alias_method("#{field}_without_arraymap", "#{field}") alias_method("#{field}", "#{field}_with_arraymap") end # Get the original object array # # Example: # # obj_mails #=> [Mail.new(name: '[email protected]'), Mail.new(name: '[email protected]')] define_method("obj_#{field}") do __send__("#{field}_without_arraymap") end # Convert the single value array to object array # # Example: # # make_mails(['[email protected]', '[email protected]']) # #=> [Mail.new(name: '[email protected]'), Mail.new(name: '[email protected]')] # # Note: # # This method uses the `#find_or_initialize_by` method internally define_method("make_#{field}") do |raw_array| return nil unless raw_array raw_array.map {|val| opts[:class].find_or_initialize_by(opts[:field] => val) } end end end end |