aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/no_touching.rb
blob: 697076bdae1de422aca8c9401d542862354a943f (plain) (blame)
1
2
3
4
5
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# frozen_string_literal: true

module ActiveRecord
  # = Active Record No Touching
  module NoTouching
    extend ActiveSupport::Concern

    module ClassMethods
      # Lets you selectively disable calls to +touch+ for the
      # duration of a block.
      #
      # ==== Examples
      #   ActiveRecord::Base.no_touching do
      #     Project.first.touch  # does nothing
      #     Message.first.touch  # does nothing
      #   end
      #
      #   Project.no_touching do
      #     Project.first.touch  # does nothing
      #     Message.first.touch  # works, but does not touch the associated project
      #   end
      #
      def no_touching(&block)
        NoTouching.apply_to(self, &block)
      end
    end

    class << self
      def apply_to(klass) #:nodoc:
        klasses.push(klass)
        yield
      ensure
        klasses.pop
      end

      def applied_to?(klass) #:nodoc:
        klasses.any? { |k| k >= klass }
      end

      private
        def klasses
          Thread.current[:no_touching_classes] ||= []
        end
    end

    # Returns +true+ if the class has +no_touching+ set, +false+ otherwise.
    #
    #   Project.no_touching do
    #     Project.first.no_touching? # true
    #     Message.first.no_touching? # false
    #   end
    #
    def no_touching?
      NoTouching.applied_to?(self.class)
    end

    def touch_later(*) # :nodoc:
      super unless no_touching?
    end

    def touch(*) # :nodoc:
      super unless no_touching?
    end
  end
end