Class: Mobility::Plugins::ActiveRecord::Dirty::MethodsBuilder

Inherits:
Mobility::Plugins::ActiveModel::Dirty::MethodsBuilder show all
Defined in:
lib/mobility/plugins/active_record/dirty.rb

Overview

Builds module which patches a few AR methods to handle changes to translated attributes just like normal attributes.

Instance Method Summary collapse

Constructor Details

#initialize(*attribute_names) ⇒ MethodsBuilder

Returns a new instance of MethodsBuilder.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/mobility/plugins/active_record/dirty.rb', line 19

def initialize(*attribute_names)
  super
  @attribute_names = attribute_names

  changes_applied_method = ::ActiveRecord::VERSION::STRING < '5.1' ? :changes_applied : :changes_internally_applied
  define_method changes_applied_method do
    @previously_changed = changes
    super()
  end

  define_method :clear_changes_information do
    @previously_changed = ActiveSupport::HashWithIndifferentAccess.new
    super()
  end

  define_method :previous_changes do
    (@previously_changed ||= ActiveSupport::HashWithIndifferentAccess.new).merge(super())
  end
end

Instance Method Details

#included(model_class) ⇒ Object

Note:

Patching has_attribute? is necessary as of AR 5.1 due to this commit. (I have voiced my opposition to this change here).

Overrides ActiveRecord::AttributeMethods::ClassMethods#has_attribute to treat fallthrough attribute methods just like "real" attribute methods.

Parameters:



45
46
47
48
49
50
51
52
53
54
# File 'lib/mobility/plugins/active_record/dirty.rb', line 45

def included(model_class)
  names = @attribute_names
  method_name_regex = /\A(#{names.join('|'.freeze)})_([a-z]{2}(_[a-z]{2})?)(=?|\??)\z/.freeze
  has_attribute = Module.new do
    define_method :has_attribute? do |attr_name|
      super(attr_name) || !!method_name_regex.match(attr_name)
    end
  end
  model_class.extend has_attribute
end