4 # Callbacks are hooks into the lifecycle of an Active Record object that allow you to trigger logic
5 # before or after an alteration of the object state. This can be used to make sure that associated and
6 # dependent objects are deleted when destroy is called (by overwriting +before_destroy+) or to massage attributes
7 # before they're validated (by overwriting +before_validation+). As an example of the callbacks initiated, consider
8 # the <tt>Base#save</tt> call:
11 # * (-) <tt>valid</tt>
12 # * (1) <tt>before_validation</tt>
13 # * (2) <tt>before_validation_on_create</tt>
14 # * (-) <tt>validate</tt>
15 # * (-) <tt>validate_on_create</tt>
16 # * (3) <tt>after_validation</tt>
17 # * (4) <tt>after_validation_on_create</tt>
18 # * (5) <tt>before_save</tt>
19 # * (6) <tt>before_create</tt>
20 # * (-) <tt>create</tt>
21 # * (7) <tt>after_create</tt>
22 # * (8) <tt>after_save</tt>
24 # That's a total of eight callbacks, which gives you immense power to react and prepare for each state in the
25 # Active Record lifecycle.
28 # class CreditCard < ActiveRecord::Base
29 # # Strip everything but digits, so the user can specify "555 234 34" or
30 # # "5552-3434" or both will mean "55523434"
31 # def before_validation_on_create
32 # self.number = number.gsub(/[^0-9]/, "") if attribute_present?("number")
36 # class Subscription < ActiveRecord::Base
37 # before_create :record_signup
41 # self.signed_up_on = Date.today
45 # class Firm < ActiveRecord::Base
46 # # Destroys the associated clients and people when the firm is destroyed
47 # before_destroy { |record| Person.destroy_all "firm_id = #{record.id}" }
48 # before_destroy { |record| Client.destroy_all "client_of = #{record.id}" }
51 # == Inheritable callback queues
53 # Besides the overwriteable callback methods, it's also possible to register callbacks through the use of the callback macros.
54 # Their main advantage is that the macros add behavior into a callback queue that is kept intact down through an inheritance
57 # class Topic < ActiveRecord::Base
58 # before_destroy :destroy_author
62 # before_destroy :destroy_readers
65 # Now, when <tt>Topic#destroy</tt> is run only +destroy_author+ is called. When <tt>Reply#destroy</tt> is run, both +destroy_author+ and
66 # +destroy_readers+ are called. Contrast this to the situation where we've implemented the save behavior through overwriteable
69 # class Topic < ActiveRecord::Base
70 # def before_destroy() destroy_author end
74 # def before_destroy() destroy_readers end
77 # In that case, <tt>Reply#destroy</tt> would only run +destroy_readers+ and _not_ +destroy_author+. So, use the callback macros when
78 # you want to ensure that a certain callback is called for the entire hierarchy, and use the regular overwriteable methods
79 # when you want to leave it up to each descendent to decide whether they want to call +super+ and trigger the inherited callbacks.
81 # *IMPORTANT:* In order for inheritance to work for the callback queues, you must specify the callbacks before specifying the
82 # associations. Otherwise, you might trigger the loading of a child before the parent has registered the callbacks and they won't
85 # == Types of callbacks
87 # There are four types of callbacks accepted by the callback macros: Method references (symbol), callback objects,
88 # inline methods (using a proc), and inline eval methods (using a string). Method references and callback objects are the
89 # recommended approaches, inline methods using a proc are sometimes appropriate (such as for creating mix-ins), and inline
90 # eval methods are deprecated.
92 # The method reference callbacks work by specifying a protected or private method available in the object, like this:
94 # class Topic < ActiveRecord::Base
95 # before_destroy :delete_parents
99 # self.class.delete_all "parent_id = #{id}"
103 # The callback objects have methods named after the callback called with the record as the only parameter, such as:
105 # class BankAccount < ActiveRecord::Base
106 # before_save EncryptionWrapper.new("credit_card_number")
107 # after_save EncryptionWrapper.new("credit_card_number")
108 # after_initialize EncryptionWrapper.new("credit_card_number")
111 # class EncryptionWrapper
112 # def initialize(attribute)
113 # @attribute = attribute
116 # def before_save(record)
117 # record.credit_card_number = encrypt(record.credit_card_number)
120 # def after_save(record)
121 # record.credit_card_number = decrypt(record.credit_card_number)
124 # alias_method :after_find, :after_save
128 # # Secrecy is committed
132 # # Secrecy is unveiled
136 # So you specify the object you want messaged on a given callback. When that callback is triggered, the object has
137 # a method by the name of the callback messaged.
139 # The callback macros usually accept a symbol for the method they're supposed to run, but you can also pass a "method string",
140 # which will then be evaluated within the binding of the callback. Example:
142 # class Topic < ActiveRecord::Base
143 # before_destroy 'self.class.delete_all "parent_id = #{id}"'
146 # Notice that single quotes (') are used so the <tt>#{id}</tt> part isn't evaluated until the callback is triggered. Also note that these
147 # inline callbacks can be stacked just like the regular ones:
149 # class Topic < ActiveRecord::Base
150 # before_destroy 'self.class.delete_all "parent_id = #{id}"',
151 # 'puts "Evaluated after parents are destroyed"'
154 # == The +after_find+ and +after_initialize+ exceptions
156 # Because +after_find+ and +after_initialize+ are called for each object found and instantiated by a finder, such as <tt>Base.find(:all)</tt>, we've had
157 # to implement a simple performance constraint (50% more speed on a simple test case). Unlike all the other callbacks, +after_find+ and
158 # +after_initialize+ will only be run if an explicit implementation is defined (<tt>def after_find</tt>). In that case, all of the
159 # callback types will be called.
161 # == <tt>before_validation*</tt> returning statements
163 # If the returning value of a +before_validation+ callback can be evaluated to +false+, the process will be aborted and <tt>Base#save</tt> will return +false+.
164 # If <tt>Base#save!</tt> is called it will raise a +RecordNotSaved+ exception.
165 # Nothing will be appended to the errors object.
167 # == Cancelling callbacks
169 # If a <tt>before_*</tt> callback returns +false+, all the later callbacks and the associated action are cancelled. If an <tt>after_*</tt> callback returns
170 # +false+, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks
171 # defined as methods on the model, which are called last.
174 after_find after_initialize before_save after_save before_create after_create before_update after_update before_validation
175 after_validation before_validation_on_create after_validation_on_create before_validation_on_update
176 after_validation_on_update before_destroy after_destroy
179 def self.included(base) #:nodoc:
180 base.extend Observable
182 [:create_or_update, :valid?, :create, :update, :destroy].each do |method|
183 base.send :alias_method_chain, method, :callbacks
186 CALLBACKS.each do |method|
187 base.class_eval <<-"end_eval"
188 def self.#{method}(*callbacks, &block)
189 callbacks << block if block_given?
190 write_inheritable_array(#{method.to_sym.inspect}, callbacks)
196 # Is called when the object was instantiated by one of the finders, like <tt>Base.find</tt>.
197 #def after_find() end
199 # Is called after the object has been instantiated by a call to <tt>Base.new</tt>.
200 #def after_initialize() end
202 # Is called _before_ <tt>Base.save</tt> (regardless of whether it's a +create+ or +update+ save).
203 def before_save() end
205 # Is called _after_ <tt>Base.save</tt> (regardless of whether it's a +create+ or +update+ save).
207 # class Contact < ActiveRecord::Base
208 # after_save { logger.info( 'New contact saved!' ) }
211 def create_or_update_with_callbacks #:nodoc:
212 return false if callback(:before_save) == false
213 result = create_or_update_without_callbacks
214 callback(:after_save)
217 private :create_or_update_with_callbacks
219 # Is called _before_ <tt>Base.save</tt> on new objects that haven't been saved yet (no record exists).
220 def before_create() end
222 # Is called _after_ <tt>Base.save</tt> on new objects that haven't been saved yet (no record exists).
223 def after_create() end
224 def create_with_callbacks #:nodoc:
225 return false if callback(:before_create) == false
226 result = create_without_callbacks
227 callback(:after_create)
230 private :create_with_callbacks
232 # Is called _before_ <tt>Base.save</tt> on existing objects that have a record.
233 def before_update() end
235 # Is called _after_ <tt>Base.save</tt> on existing objects that have a record.
236 def after_update() end
238 def update_with_callbacks #:nodoc:
239 return false if callback(:before_update) == false
240 result = update_without_callbacks
241 callback(:after_update)
244 private :update_with_callbacks
246 # Is called _before_ <tt>Validations.validate</tt> (which is part of the <tt>Base.save</tt> call).
247 def before_validation() end
249 # Is called _after_ <tt>Validations.validate</tt> (which is part of the <tt>Base.save</tt> call).
250 def after_validation() end
252 # Is called _before_ <tt>Validations.validate</tt> (which is part of the <tt>Base.save</tt> call) on new objects
253 # that haven't been saved yet (no record exists).
254 def before_validation_on_create() end
256 # Is called _after_ <tt>Validations.validate</tt> (which is part of the <tt>Base.save</tt> call) on new objects
257 # that haven't been saved yet (no record exists).
258 def after_validation_on_create() end
260 # Is called _before_ <tt>Validations.validate</tt> (which is part of the <tt>Base.save</tt> call) on
261 # existing objects that have a record.
262 def before_validation_on_update() end
264 # Is called _after_ <tt>Validations.validate</tt> (which is part of the <tt>Base.save</tt> call) on
265 # existing objects that have a record.
266 def after_validation_on_update() end
268 def valid_with_callbacks? #:nodoc:
269 return false if callback(:before_validation) == false
270 if new_record? then result = callback(:before_validation_on_create) else result = callback(:before_validation_on_update) end
271 return false if result == false
273 result = valid_without_callbacks?
275 callback(:after_validation)
276 if new_record? then callback(:after_validation_on_create) else callback(:after_validation_on_update) end
281 # Is called _before_ <tt>Base.destroy</tt>.
283 # Note: If you need to _destroy_ or _nullify_ associated records first,
284 # use the <tt>:dependent</tt> option on your associations.
285 def before_destroy() end
287 # Is called _after_ <tt>Base.destroy</tt> (and all the attributes have been frozen).
289 # class Contact < ActiveRecord::Base
290 # after_destroy { |record| logger.info( "Contact #{record.id} was destroyed." ) }
292 def after_destroy() end
293 def destroy_with_callbacks #:nodoc:
294 return false if callback(:before_destroy) == false
295 result = destroy_without_callbacks
296 callback(:after_destroy)
304 callbacks_for(method).each do |callback|
305 result = case callback
309 eval(callback, binding)
313 if callback.respond_to?(method)
314 callback.send(method, self)
316 raise ActiveRecordError, "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."
319 return false if result == false
322 result = send(method) if respond_to_without_attributes?(method)
327 def callbacks_for(method)
328 self.class.read_inheritable_attribute(method.to_sym) or []
331 def invoke_and_notify(method)
333 send(method) if respond_to_without_attributes?(method)
336 def notify(method) #:nodoc:
338 self.class.notify_observers(method, self)