module DirtyAssociations::ClassMethods

Public Instance Methods

monitor_association_changes(association) click to toggle source

Creates methods that allows an association to be monitored.

The association parameter should be a string or symbol representing the name of an association.

Calls superclass method
# File lib/dirty_associations.rb, line 15
def monitor_association_changes(association)
  define_method "#{association}=" do |value|
    attribute_will_change!(association.to_s) if _association_will_change?(association, value)
    super(value)
  end

  ids = "#{association.to_s.singularize}_ids"

  define_method "#{ids}=" do |value|
    attribute_will_change!(association.to_s) if _ids_will_change?(ids, value)
    super(value)
  end

  define_method "#{association}_attributes=" do |value|
    attribute_will_change!(association.to_s) if _nested_attributes_will_change?(value)
    super(value)
  end

  [association, ids].each do |name|
    define_method "#{name}_change" do
      changes[name]
    end

    define_method "#{name}_changed?" do
      changes.has_key?(association.to_s)
    end

    define_method "#{name}_previously_changed?" do
      previous_changes.has_key?(association.to_s)
    end
  end
end