Module: AnafHabtm::ActiveRecord
- Defined in:
- lib/anaf_active_record.rb
Instance Method Summary collapse
- #anaf_habtm(association, options = {}, &block) ⇒ Object
- #named_association(member, attribute, opts = {}) ⇒ Object
Instance Method Details
#anaf_habtm(association, options = {}, &block) ⇒ Object
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/anaf_active_record.rb', line 4 def anaf_habtm(association, ={}, &block) class_eval do # Define a proc that will look up the (potentially) existing object finder = proc {|id| association.to_s.singularize.camelize.constantize.where(:id=>id).first } # Define a proc that will set the association collection set_collection = proc {|me, coll| me.send("#{association.to_s.tableize}=", coll)} has_and_belongs_to_many association.to_sym, # Define the actual association setter. define_method "#{association.to_s.tableize}_attributes=", lambda{|attributes_for_association| coll = [] attributes_for_association.each_value do |params| next if params["_destroy"] == "1" obj = finder.call(params["id"]) if params.has_key?("id") params.extend(AnafHabtm::HashExtension) # ActiveRecord::Base.attributes=() doesn't like extra parameters. coll << block.call(params.copy_without_destroy, obj) end set_collection.call(self, coll) } end end |
#named_association(member, attribute, opts = {}) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/anaf_active_record.rb', line 29 def named_association(member, attribute, opts={}) member = member.to_s klass = opts.has_key?(:class) ? opts[:class_name] : member.to_s.singularize.camelize attribute = attribute.to_s if opts.has_key?(:create) class_eval "def #{member}_#{attribute}=(#{attribute}); return if #{attribute}.blank? self.#{member} = #{klass}.find_or_create_by_#{attribute}(#{attribute}) end;" else class_eval "def #{member}_#{attribute}=(#{attribute}); self.#{member} = #{klass}.find_by_#{attribute}(#{attribute}) unless #{attribute}.blank?; end;" end class_eval "def #{member}_#{attribute}; #{member}.#{attribute} if #{member}; end;" end |