module Mobility::Plugins::ActiveModel::Dirty

Dirty tracking for models which include the ActiveModel::Dirty module.

Assuming we have an attribute title, this module will add support for the following methods:

The following methods are also patched to work with translated attributes:

In addition, the following ActiveModel attribute handler methods are also patched to work with translated attributes:

(When using these methods, you must pass the attribute name along with its locale suffix, so title_en, title_pt_br, etc.)

Other methods are also included for ActiveRecord models, see documentation on the ActiveRecord dirty plugin for more information.

@see api.rubyonrails.org/classes/ActiveModel/Dirty.html Rails documentation for Active Model Dirty module

Constants

HandlerMethods

Module which defines generic handler methods like attribute_changed? that are patched to work with translated attributes.

Private Class Methods

append_locale(attr_name) click to toggle source
# File lib/mobility/plugins/active_model/dirty.rb, line 110
def self.append_locale(attr_name)
  Mobility.normalize_locale_accessor(attr_name)
end

Private Instance Methods

active_model_dirty_class?(klass) click to toggle source
# File lib/mobility/plugins/active_model/dirty.rb, line 75
def active_model_dirty_class?(klass)
  klass.ancestors.include?(::ActiveModel::Dirty)
end
define_dirty_methods(attribute_names) click to toggle source
Calls superclass method
# File lib/mobility/plugins/active_model/dirty.rb, line 79
def define_dirty_methods(attribute_names)
  attribute_names.each do |name|
    dirty_handler_methods.each_pattern(name) do |method_name, attribute_method|
      define_method(method_name) do |*args|
        # for %s_changed?(from:, to:) pattern
        if (kwargs = args.last).is_a?(Hash)
          mutations_from_mobility.send(attribute_method, Dirty.append_locale(name), *args[0,-1], **kwargs)
        else
          mutations_from_mobility.send(attribute_method, Dirty.append_locale(name), *args)
        end
      end
    end

    define_method "restore_#{name}!" do
      locale_accessor = Dirty.append_locale(name)
      if mutations_from_mobility.attribute_changed?(locale_accessor)
        __send__("#{name}=", mutations_from_mobility.attribute_was(locale_accessor))
        mutations_from_mobility.restore_attribute!(locale_accessor)
      end
    end
  end

  # This private method override is necessary to make
  # +restore_attributes+ (which is public) work with translated
  # attributes.
  define_method :restore_attribute! do |attr|
    attribute_names.include?(attr.to_s) ? send("restore_#{attr}!") : super(attr)
  end
  private :restore_attribute!
end
dirty_handler_methods() click to toggle source

Overridden in AR::Dirty plugin to define a different HandlerMethods module

# File lib/mobility/plugins/active_model/dirty.rb, line 71
def dirty_handler_methods
  HandlerMethods
end