aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/callbacks.rb
blob: f049189b9af166e9444b844286abc0db1bd80ae5 (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
require 'active_support/core_ext/array/extract_options'

module ActiveSupport
  # Callbacks are hooks into the lifecycle of an object that allow you to trigger logic
  # before or after an alteration of the object state.
  #
  # Mixing in this module allows you to define callbacks in your class.
  #
  # Example:
  #   class Storage
  #     include ActiveSupport::Callbacks
  #
  #     define_callbacks :before_save, :after_save
  #   end
  #
  #   class ConfigStorage < Storage
  #     before_save :saving_message
  #     def saving_message
  #       puts "saving..."
  #     end
  #
  #     after_save do |object|
  #       puts "saved"
  #     end
  #
  #     def save
  #       run_callbacks(:before_save)
  #       puts "- save"
  #       run_callbacks(:after_save)
  #     end
  #   end
  #
  #   config = ConfigStorage.new
  #   config.save
  #
  # Output:
  #   saving...
  #   - save
  #   saved
  #
  # Callbacks from parent classes are inherited.
  #
  # Example:
  #   class Storage
  #     include ActiveSupport::Callbacks
  #
  #     define_callbacks :before_save, :after_save
  #
  #     before_save :prepare
  #     def prepare
  #       puts "preparing save"
  #     end
  #   end
  #
  #   class ConfigStorage < Storage
  #     before_save :saving_message
  #     def saving_message
  #       puts "saving..."
  #     end
  #
  #     after_save do |object|
  #       puts "saved"
  #     end
  #
  #     def save
  #       run_callbacks(:before_save)
  #       puts "- save"
  #       run_callbacks(:after_save)
  #     end
  #   end
  #
  #   config = ConfigStorage.new
  #   config.save
  #
  # Output:
  #   preparing save
  #   saving...
  #   - save
  #   saved
  module Callbacks
    class CallbackChain < Array
      def self.build(kind, *methods, &block)
        methods, options = extract_options(*methods, &block)
        methods.map! { |method| Callback.new(kind, method, options) }
        new(methods)
      end

      def run(object, options = {}, &terminator)
        enumerator = options[:enumerator] || :each

        unless block_given?
          send(enumerator) { |callback| callback.call(object) }
        else
          send(enumerator) do |callback|
            result = callback.call(object)
            break result if terminator.call(result, object)
          end
        end
      end

      # TODO: Decompose into more Array like behavior
      def replace_or_append!(chain)
        if index = index(chain)
          self[index] = chain
        else
          self << chain
        end
        self
      end

      def find(callback, &block)
        select { |c| c == callback && (!block_given? || yield(c)) }.first
      end

      def delete(callback)
        super(callback.is_a?(Callback) ? callback : find(callback))
      end

      private
        def self.extract_options(*methods, &block)
          methods.flatten!
          options = methods.extract_options!
          methods << block if block_given?
          return methods, options
        end

        def extract_options(*methods, &block)
          self.class.extract_options(*methods, &block)
        end
    end

    class Callback
      attr_reader :kind, :method, :identifier, :options

      def initialize(kind, method, options = {})
        @kind       = kind
        @method     = method
        @identifier = options[:identifier]
        @options    = options
      end

      def ==(other)
        case other
        when Callback
          (self.identifier && self.identifier == other.identifier) || self.method == other.method
        else
          (self.identifier && self.identifier == other) || self.method == other
        end
      end

      def eql?(other)
        self == other
      end

      def dup
        self.class.new(@kind, @method, @options.dup)
      end

      def hash
        if @identifier
          @identifier.hash
        else
          @method.hash
        end
      end

      def call(*args, &block)
        evaluate_method(method, *args, &block) if should_run_callback?(*args)
      rescue LocalJumpError
        raise ArgumentError,
          "Cannot yield from a Proc type filter. The Proc must take two " +
          "arguments and execute #call on the second argument."
      end

      private
        def evaluate_method(method, *args, &block)
          case method
            when Symbol
              object = args.shift
              object.send(method, *args, &block)
            when String
              eval(method, args.first.instance_eval { binding })
            when Proc, Method
              method.call(*args, &block)
            else
              if method.respond_to?(kind)
                method.send(kind, *args, &block)
              else
                raise ArgumentError,
                  "Callbacks must be a symbol denoting the method to call, a string to be evaluated, " +
                  "a block to be invoked, or an object responding to the callback method."
              end
          end
        end

        def should_run_callback?(*args)
          [options[:if]].flatten.compact.all? { |a| evaluate_method(a, *args) } &&
          ![options[:unless]].flatten.compact.any? { |a| evaluate_method(a, *args) }
        end
    end

    def self.included(base)
      base.extend ClassMethods
    end

    module ClassMethods
      def define_callbacks(*callbacks)
        callbacks.each do |callback|
          class_eval <<-"end_eval", __FILE__, __LINE__ + 1
            def self.#{callback}(*methods, &block)                             # def self.before_save(*methods, &block)
              callbacks = CallbackChain.build(:#{callback}, *methods, &block)  #   callbacks = CallbackChain.build(:before_save, *methods, &block)
              @#{callback}_callbacks ||= CallbackChain.new                     #   @before_save_callbacks ||= CallbackChain.new
              @#{callback}_callbacks.concat callbacks                          #   @before_save_callbacks.concat callbacks
            end                                                                # end
                                                                               #
            def self.#{callback}_callback_chain                                # def self.before_save_callback_chain
              @#{callback}_callbacks ||= CallbackChain.new                     #   @before_save_callbacks ||= CallbackChain.new
                                                                               #
              if superclass.respond_to?(:#{callback}_callback_chain)           #   if superclass.respond_to?(:before_save_callback_chain)
                CallbackChain.new(                                             #     CallbackChain.new(
                  superclass.#{callback}_callback_chain +                      #       superclass.before_save_callback_chain +
                  @#{callback}_callbacks                                       #       @before_save_callbacks
                )                                                              #     )
              else                                                             #   else
                @#{callback}_callbacks                                         #     @before_save_callbacks
              end                                                              #   end
            end                                                                # end
          end_eval
        end
      end
    end

    # Runs all the callbacks defined for the given options.
    #
    # If a block is given it will be called after each callback receiving as arguments:
    #
    #  * the result from the callback
    #  * the object which has the callback
    #
    # If the result from the block evaluates to false, the callback chain is stopped.
    #
    # Example:
    #   class Storage
    #     include ActiveSupport::Callbacks
    #
    #     define_callbacks :before_save, :after_save
    #   end
    #
    #   class ConfigStorage < Storage
    #     before_save :pass
    #     before_save :pass
    #     before_save :stop
    #     before_save :pass
    #
    #     def pass
    #       puts "pass"
    #     end
    #
    #     def stop
    #       puts "stop"
    #       return false
    #     end
    #
    #     def save
    #       result = run_callbacks(:before_save) { |result, object| result == false }
    #       puts "- save" if result
    #     end
    #   end
    #
    #   config = ConfigStorage.new
    #   config.save
    #
    # Output:
    #   pass
    #   pass
    #   stop
    def run_callbacks(kind, options = {}, &block)
      self.class.send("#{kind}_callback_chain").run(self, options, &block)
    end
  end
end