Module: GuardAgainstPhysicalDelete::SupportCounterCache::Associations::Builder::BelongsTo

Defined in:
lib/guard_against_physical_delete/support_counter_cache/associations/builder/belongs_to.rb

Class Method Summary collapse

Class Method Details

.included(obj) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/guard_against_physical_delete/support_counter_cache/associations/builder/belongs_to.rb', line 6

def self.included(obj)
  class << obj
    prepend MethodOverrides

    private

    def add_logical_delete_counter_cache_methods(mixin)
      mixin.class_eval do
        def adjust_counter_caches_for_logical_deletion(reflection)
          if attribute_before_last_save(logical_delete_column).nil? && read_attribute(logical_delete_column)
            reflection.klass.decrement_counter(
              reflection.counter_cache_column,
              attribute_before_last_save(reflection.foreign_key)
            )
          elsif attribute_before_last_save(logical_delete_column) && read_attribute(logical_delete_column).nil?
            reflection.klass.increment_counter(
              reflection.counter_cache_column,
              attribute_before_last_save(reflection.foreign_key)
            )
          end
        end

        # Polyfill for Rails < 5.1, not that it's perfectly compatible.
        if ActiveRecord.version < Gem::Version.new('5.1.0')
          # @param [#to_s] attr_name
          # @return [Object]
          def attribute_before_last_save(attr_name)
            __send__("#{attr_name}_was")
          end

          # @param [#to_s] attr_name
          # @return [Boolean]
          def saved_change_to_attribute?(attr_name)
            __send__("#{attr_name}_changed?")
          end
        end
      end

      mixin.redefine_method("belongs_to_counter_cache_after_update_for_#{name}") do
        # do nothing
      end if mixin.method_defined?("belongs_to_counter_cache_after_update_for_#{name}")
    end
  end
end