diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb index 88958f4583..e375037b5b 100644 --- a/activerecord/lib/active_record/callbacks.rb +++ b/activerecord/lib/active_record/callbacks.rb @@ -104,16 +104,12 @@ module ActiveRecord # The callback objects have methods named after the callback called with the record as the only parameter, such as: # # class BankAccount < ActiveRecord::Base - # before_save EncryptionWrapper.new("credit_card_number") - # after_save EncryptionWrapper.new("credit_card_number") - # after_initialize EncryptionWrapper.new("credit_card_number") + # before_save EncryptionWrapper.new + # after_save EncryptionWrapper.new + # after_initialize EncryptionWrapper.new # end # # class EncryptionWrapper - # def initialize(attribute) - # @attribute = attribute - # end - # # def before_save(record) # record.credit_card_number = encrypt(record.credit_card_number) # end @@ -135,7 +131,39 @@ module ActiveRecord # end # # So you specify the object you want messaged on a given callback. When that callback is triggered, the object has - # a method by the name of the callback messaged. + # a method by the name of the callback messaged. You can make these callbacks more flexible by passing in other + # initialization data such as the name of the attribute to work with: + # + # class BankAccount < ActiveRecord::Base + # before_save EncryptionWrapper.new("credit_card_number") + # after_save EncryptionWrapper.new("credit_card_number") + # after_initialize EncryptionWrapper.new("credit_card_number") + # end + # + # class EncryptionWrapper + # def initialize(attribute) + # @attribute = attribute + # end + # + # def before_save(record) + # record.send("#{@attribute}=", encrypt(record.send("#{@attribute}"))) + # end + # + # def after_save(record) + # record.send("#{@attribute}=", decrypt(record.send("#{@attribute}"))) + # end + # + # alias_method :after_find, :after_save + # + # private + # def encrypt(value) + # # Secrecy is committed + # end + # + # def decrypt(value) + # # Secrecy is unveiled + # end + # end # # The callback macros usually accept a symbol for the method they're supposed to run, but you can also pass a "method string", # which will then be evaluated within the binding of the callback. Example: