Sha256: 871814ccc36cb91a2bf7d2c040b7b513b8b201a64b5e6265d98c1cdb5e69cedd
Contents?: true
Size: 1.68 KB
Versions: 7
Compression:
Stored size: 1.68 KB
Contents
# AnafHabtm module ActiveRecordExtensions def anaf_habtm(association, options={}, &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, options # 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(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 def named_association(member, klass, attribute, create=nil) member = member.to_s klass = klass.name attribute = attribute.to_s if 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 end
Version data entries
7 entries across 7 versions & 1 rubygems