root/tags/rel_2-0-2/activerecord/lib/active_record/callbacks.rb
| Revision 8301, 13.3 kB (checked in by david, 1 year ago) | |
|---|---|
| |
| Line | |
|---|---|
| 1 | require 'observer' |
| 2 | |
| 3 | module ActiveRecord |
| 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: |
| 9 | # |
| 10 | # * (-) <tt>save</tt> |
| 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> |
| 23 | # |
| 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. |
| 26 | # |
| 27 | # Examples: |
| 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") |
| 33 | # end |
| 34 | # end |
| 35 | # |
| 36 | # class Subscription < ActiveRecord::Base |
| 37 | # before_create :record_signup |
| 38 | # |
| 39 | # private |
| 40 | # def record_signup |
| 41 | # self.signed_up_on = Date.today |
| 42 | # end |
| 43 | # end |
| 44 | # |
| 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}" } |
| 49 | # end |
| 50 | # |
| 51 | # == Inheritable callback queues |
| 52 | # |
| 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 |
| 55 | # hierarchy. Example: |
| 56 | # |
| 57 | # class Topic < ActiveRecord::Base |
| 58 | # before_destroy :destroy_author |
| 59 | # end |
| 60 | # |
| 61 | # class Reply < Topic |
| 62 | # before_destroy :destroy_readers |
| 63 | # end |
| 64 | # |
| 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 |
| 67 | # methods: |
| 68 | # |
| 69 | # class Topic < ActiveRecord::Base |
| 70 | # def before_destroy() destroy_author end |
| 71 | # end |
| 72 | # |
| 73 | # class Reply < Topic |
| 74 | # def before_destroy() destroy_readers end |
| 75 | # end |
| 76 | # |
| 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. |
| 80 | # |
| 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 |
| 83 | # be inherited. |
| 84 | # |
| 85 | # == Types of callbacks |
| 86 | # |
| 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. |
| 91 | # |
| 92 | # The method reference callbacks work by specifying a protected or private method available in the object, like this: |
| 93 | # |
| 94 | # class Topic < ActiveRecord::Base |
| 95 | # before_destroy :delete_parents |
| 96 | # |
| 97 | # private |
| 98 | # def delete_parents |
| 99 | # self.class.delete_all "parent_id = #{id}" |
| 100 | # end |
| 101 | # end |
| 102 | # |
| 103 | # The callback objects have methods named after the callback called with the record as the only parameter, such as: |
| 104 | # |
| 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") |
| 109 | # end |
| 110 | # |
| 111 | # class EncryptionWrapper |
| 112 | # def initialize(attribute) |
| 113 | # @attribute = attribute |
| 114 | # end |
| 115 | # |
| 116 | # def before_save(record) |
| 117 | # record.credit_card_number = encrypt(record.credit_card_number) |
| 118 | # end |
| 119 | # |
| 120 | # def after_save(record) |
| 121 | # record.credit_card_number = decrypt(record.credit_card_number) |
| 122 | # end |
| 123 | # |
| 124 | # alias_method :after_find, :after_save |
| 125 | # |
| 126 | # private |
| 127 | # def encrypt(value) |
| 128 | # # Secrecy is committed |
| 129 | # end |
| 130 | # |
| 131 | # def decrypt(value) |
| 132 | # # Secrecy is unveiled |
| 133 | # end |
| 134 | # end |
| 135 | # |
| 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. |
| 138 | # |
| 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: |
| 141 | # |
| 142 | # class Topic < ActiveRecord::Base |
| 143 | # before_destroy 'self.class.delete_all "parent_id = #{id}"' |
| 144 | # end |
| 145 | # |
| 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: |
| 148 | # |
| 149 | # class Topic < ActiveRecord::Base |
| 150 | # before_destroy 'self.class.delete_all "parent_id = #{id}"', |
| 151 | # 'puts "Evaluated after parents are destroyed"' |
| 152 | # end |
| 153 | # |
| 154 | # == The +after_find+ and +after_initialize+ exceptions |
| 155 | # |
| 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. |
| 160 | # |
| 161 | # == <tt>before_validation*</tt> returning statements |
| 162 | # |
| 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. |
| 166 | # |
| 167 | # == Canceling callbacks |
| 168 | # |
| 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. |
| 172 | module Callbacks |
| 173 | CALLBACKS = %w( |
| 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 |
| 177 | ) |
| 178 | |
| 179 | def self.included(base) #:nodoc: |
| 180 | base.extend Observable |
| 181 | |
| 182 | [:create_or_update, :valid?, :create, :update, :destroy].each do |method| |
| 183 | base.send :alias_method_chain, method, :callbacks |
| 184 | end |
| 185 | |
| 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) |
| 191 | end |
| 192 | end_eval |
| 193 | end |
| 194 | end |
| 195 | |
| 196 | # Is called when the object was instantiated by one of the finders, like <tt>Base.find</tt>. |
| 197 | #def after_find() end |
| 198 | |
| 199 | # Is called after the object has been instantiated by a call to <tt>Base.new</tt>. |
| 200 | #def after_initialize() end |
| 201 | |
| 202 | # Is called _before_ <tt>Base.save</tt> (regardless of whether it's a +create+ or +update+ save). |
| 203 | def before_save() end |
| 204 | |
| 205 | # Is called _after_ <tt>Base.save</tt> (regardless of whether it's a +create+ or +update+ save). |
| 206 | # |
| 207 | # class Contact < ActiveRecord::Base |
| 208 | # after_save { logger.info( 'New contact saved!' ) } |
| 209 | # end |
| 210 | def after_save() end |
| 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) |
| 215 | result |
| 216 | end |
| 217 | private :create_or_update_with_callbacks |
| 218 | |
| 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 |
| 221 | |
| 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) |
| 228 | result |
| 229 | end |
| 230 | private :create_with_callbacks |
| 231 | |
| 232 | # Is called _before_ <tt>Base.save</tt> on existing objects that have a record. |
| 233 | def before_update() end |
| 234 | |
| 235 | # Is called _after_ <tt>Base.save</tt> on existing objects that have a record. |
| 236 | def after_update() end |
| 237 | |
| 238 | def update_with_callbacks #:nodoc: |
| 239 | return false if callback(:before_update) == false |
| 240 | result = update_without_callbacks |
| 241 | callback(:after_update) |
| 242 | result |
| 243 | end |
| 244 | private :update_with_callbacks |
| 245 | |
| 246 | # Is called _before_ <tt>Validations.validate</tt> (which is part of the <tt>Base.save</tt> call). |
| 247 | def before_validation() end |
| 248 | |
| 249 | # Is called _after_ <tt>Validations.validate</tt> (which is part of the <tt>Base.save</tt> call). |
| 250 | def after_validation() end |
| 251 | |
| 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 |
| 255 | |
| 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 |
| 259 | |
| 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 |
| 263 | |
| 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 |
| 267 | |
| 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 |
| 272 | |
| 273 | result = valid_without_callbacks? |
| 274 | |
| 275 | callback(:after_validation) |
| 276 | if new_record? then callback(:after_validation_on_create) else callback(:after_validation_on_update) end |
| 277 | |
| 278 | return result |
| 279 | end |
| 280 | |
| 281 | # Is called _before_ <tt>Base.destroy</tt>. |
| 282 | # |
| 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 |
| 286 | |
| 287 | # Is called _after_ <tt>Base.destroy</tt> (and all the attributes have been frozen). |
| 288 | # |
| 289 | # class Contact < ActiveRecord::Base |
| 290 | # after_destroy { |record| logger.info( "Contact #{record.id} was destroyed." ) } |
| 291 | # end |
| 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) |
| 297 | result |
| 298 | end |
| 299 | |
| 300 | private |
| 301 | def callback(method) |
| 302 | notify(method) |
| 303 | |
| 304 | callbacks_for(method).each do |callback| |
| 305 | result = case callback |
| 306 | when Symbol |
| 307 | self.send(callback) |
| 308 | when String |
| 309 | eval(callback, binding) |
| 310 | when Proc, Method |
| 311 | callback.call(self) |
| 312 | else |
| 313 | if callback.respond_to?(method) |
| 314 | callback.send(method, self) |
| 315 | else |
| 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." |
| 317 | end |
| 318 | end |
| 319 | return false if result == false |
| 320 | end |
| 321 | |
| 322 | result = send(method) if respond_to_without_attributes?(method) |
| 323 | |
| 324 | return result |
| 325 | end |
| 326 | |
| 327 | def callbacks_for(method) |
| 328 | self.class.read_inheritable_attribute(method.to_sym) or [] |
| 329 | end |
| 330 | |
| 331 | def invoke_and_notify(method) |
| 332 | notify(method) |
| 333 | send(method) if respond_to_without_attributes?(method) |
| 334 | end |
| 335 | |
| 336 | def notify(method) #:nodoc: |
| 337 | self.class.changed |
| 338 | self.class.notify_observers(method, self) |
| 339 | end |
| 340 | end |
| 341 | end |
Note: See TracBrowser for help on using the browser.