Home > Articles > Web Development

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

9.2 Callbacks

This advanced feature of Active Record allows the savvy developer to attach behavior at a variety of different points along a model’s life cycle, such as after initialization; before database records are inserted, updated, or removed; and so on.

Callbacks can do a variety of tasks, ranging from simple things such as the logging and massaging of attribute values prior to validation to complex calculations. Callbacks can halt the execution of the life cycle process taking place. Some callbacks can even modify the behavior of the model class on the fly. We’ll cover all those scenarios in this section, but first let’s get a taste of what a callback looks like. Check out the following silly example:


1 class Beethoven < ActiveRecord::Base
2   before_destroy :last_words
3
4   protected
5
6   def last_words
7     logger.info "Friends applaud, the comedy is over"
8   end
9 end

So prior to dying (ehrm, being destroyed), the last words of the Beethoven class will always be logged for posterity. As we’ll see soon, there are 14 different opportunities to add behavior to your model in this fashion. Before we get to that list, let’s cover the mechanics of registering a callback.

9.2.1 One-Liners

Now if (and only if) your callback routine is really short,2 you can add it by passing a block to the callback macro. We’re talking one-liners!


class Napoleon < ActiveRecord::Base
  before_destroy { logger.info "Josephine..." }
  ...
end

Since Rails 3, the block passed to a callback is executed via instance_eval so that its scope is the record itself (versus needing to act on a passed-in record variable). The following example implements “paranoid” model behavior, covered later in the chapter.


1 class Account < ActiveRecord::Base
2   before_destroy { self.update_attribute(:deleted_at, Time.now); false }
3   ...

9.2.2 Protected or Private

Except when you’re using a block, the access level for callback methods should always be protected or private. It should never be public, since callbacks should never be called from code outside the model.

Believe it or not, there are even more ways to implement callbacks, but we’ll cover those techniques later in the chapter. For now, let’s look at the lists of callback hooks available.

9.2.3 Matched before/after Callbacks

In total, there are 19 types of callbacks you can register on your models! Thirteen of them are matching before/after callback pairs, such as before_validation and after_validation. Four of them are around callbacks, such as around_save. (The other two, after_initialize and after_find, are special, and we’ll discuss them later in this section.)

9.2.3.1 List of Callbacks

This is the list of callback hooks available during a save operation. (The list varies slightly depending on whether you’re saving a new or existing record.)

  • before_validation
  • after_validation
  • before_save
  • around_save
  • before_create (for new records) and before_update (for existing records)
  • around_create (for new records) and around_update (for existing records)
  • after_create (for new records) and after_update (for existing records)
  • after_save

Delete operations have their own callbacks:

  • before_destroy
  • around_destroy, which executes a DELETE database statement on yield
  • after_destroy, which is called after record has been removed from the database and all attributes have been frozen (readonly)

Callbacks may be limited to specific Active Record life cycles (:create, :update, :destroy) by explicitly defining which ones can trigger it using the :on option. The :on option may accept a single lifecycle (like on: :create) or an array of life cycles (like on: [:create, :update]).

# Run only on create.
before_validation :some_callback, on: :create

Additionally, transactions have callbacks as well for when you want actions to occur after the database is guaranteed to be in a permanent state. Note that only “after” callbacks exist here due to the nature of transactions—it’s a bad idea to be able to interfere with the actual operation itself.

  • after_commit
  • after_rollback
  • after_touch

9.2.4 Halting Execution

If you return a boolean false (not nil) from a callback method, Active Record halts the execution chain. No further callbacks are executed. The save method will return false, and save! will raise a RecordNotSaved error.

Keep in mind that since the last expression of a Ruby method is returned implicitly, it is a pretty common bug to write a callback that halts execution unintentionally. If you have an object with callbacks that mysteriously fails to save, make sure you aren’t returning false by mistake.

9.2.5 Callback Usages

Of course, the callback you should use for a given situation depends on what you’re trying to accomplish. The best I can do is to serve up some examples to inspire you with your own code.

9.2.5.1 Cleaning Up Attribute Formatting with before_validation on Create

The most common examples of using before_validation callbacks have to do with cleaning up user-entered attributes. For example, the following CreditCard class cleans up its number attribute so that false negatives don’t occur on validation:


1 class CreditCard < ActiveRecord::Base
2   before_validation on: :create do
3     # Strip everything in the number except digits.
4     self.number = number.gsub(/[^0-9]/, "")
5   end
6 end

9.2.5.2 Geocoding with before_save

Assume that you have an application that tracks addresses and has mapping features. Addresses should always be geocoded before saving so that they can be displayed rapidly on a map later.3

As is often the case, the wording of the requirement itself points you in the direction of the before_save callback:


 1 class Address < ActiveRecord::Base
 2
 3   before_save :geocode
 4   validates_presence_of :street, :city, :state, :country
 5   ...
 6
 7   def to_s
 8     [street, city, state, country].compact.join(', ')
 9   end
10
11   protected
12
13   def geocode
14     result = Geocoder.coordinates(to_s)
15     self.latitude = result.first
16     self.longitude = result.last
17   end
18 end

Before we move on, there are a couple of additional considerations. The preceding code works great if the geocoding succeeds, but what if it doesn’t? Do we still want to allow the record to be saved? If not, we should halt the execution chain:


1 def geolocate
2   result = Geocoder.coordinates(to_s)
3   return false if result.empty? # halt execution
4
5   self.latitude = result.first
6   self.longitude = result.last
7 end

The only problem remaining is that we give the rest of our code (and by extension, the end user) no indication of why the chain was halted. Even though we’re not in a validation routine, I think we can put the errors collection to good use here:

 
 1 def geolocate
 2   result = Geocoder.coordinates(to_s)
 3   if result.present?
 4     self.latitude = result.first
 5     self.longitude = result.last
 6   else
 7     errors[:base] << "Geocoding failed. Please check address."
 8     false
 9   end
10 end

If the geocoding fails, we add a base error message (for the whole object) and halt execution so that the record is not saved.

9.2.5.3 Exercise Your Paranoia with before_destroy

What if your application has to handle important kinds of data that, once entered, should never be deleted? Perhaps it would make sense to hook into Active Record’s destroy mechanism and somehow mark the record as deleted instead?

The following example depends on the accounts table having a deleted_at datetime column.


1 class Account < ActiveRecord::Base
2   before_destroy do
3     self.update_attribute(:deleted_at, Time.current)
4     false
5   end
6
7   ...
8 end

After the deleted_at column is populated with the current time, we return false in the callback to halt execution. This ensures that the underlying record is not actually deleted from the database.4

It’s probably worth mentioning that there are ways that Rails allows you to unintentionally circumvent before_destroy callbacks:

  • The delete and delete_all class methods of ActiveRecord::Base are almost identical. They remove rows directly from the database without instantiating the corresponding model instances, which means no callbacks will occur.
  • Model objects in associations defined with the option dependent: :delete_all will be deleted directly from the database when removed from the collection using the association’s clear or delete methods.

9.2.5.4 Cleaning Up Associated Files with after_destroy

Model objects that have files associated with them, such as attachment records and uploaded images, can clean up after themselves when deleted using the after_destroy callback. The following method from Thoughtbot’s Paperclip5 gem is a good example:


1 # Destroys the file. Called in an after_destroy callback.
2 def destroy_attached_files
3   Paperclip.log("Deleting attachments.")
4   each_attachment do |name, attachment|
5     attachment.send(:flush_deletes)
6   end
7 end

9.2.6 Special Callbacks: after_initialize and after_find

The after_initialize callback is invoked whenever a new Active Record model is instantiated (either from scratch or from the database). Having it available prevents you from having to muck around with overriding the actual initialize method.

The after_find callback is invoked whenever Active Record loads a model object from the database and is actually called before after_initialize if both are implemented. Because after_find and after_initialize are called for each object found and instantiated by finders, performance constraints dictate that they can only be added as methods and not via the callback macros.

What if you want to run some code only the first time a model is ever instantiated and not after each database load? There is no native callback for that scenario, but you can do it using the after_initialize callback. Just add a condition that checks to see if it is a new record:


1 after_initialize do
2   if new_record?
3     ...
4   end
5 end

In a number of Rails apps that I’ve written, I’ve found it useful to capture user preferences in a serialized hash associated with the User object. The serialize feature of Active Record models makes this possible, since it transparently persists Ruby object graphs to a text column in the database. Unfortunately, you can’t pass it a default value, so I have to set one myself:


 1 class User < ActiveRecord::Base
 2   serialize :preferences # defaults to nil
 3   ...
 4
 5   protected
 6
 7   def after_initialize
 8     self.preferences ||= Hash.new
 9   end
10 end

Using the after_initialize callback, I can automatically populate the preferences attribute of my user model with an empty hash, so that I never have to worry about it being nil when I access it with code such as user.preferences[:show_help_text] = false.

Ruby’s metaprogramming capabilities combined with the ability to run code whenever a model is loaded using the after_find callback are a powerful mix. Since we’re not done learning about callbacks yet, we’ll come back to uses of after_find later on in the chapter in the section “Modifying Active Record Classes at Runtime.”

9.2.7 Callback Classes

It is common enough to want to reuse callback code for more than one object that Rails provides a way to write callback classes. All you have to do is pass a given callback queue an object that responds to the name of the callback and takes the model object as a parameter.

Here’s our paranoid example from the previous section as a callback class:


1 class MarkDeleted
2   def self.before_destroy(model)
3      model.update_attribute(:deleted_at, Time.current)
4      false
5   end
6 end

The behavior of MarkDeleted is stateless, so I added the callback as a class method. Now you don’t have to instantiate MarkDeleted objects for no good reason. All you do is pass the class to the callback queue for whichever models you want to have the mark-deleted behavior:


1 class Account < ActiveRecord::Base
2   before_destroy MarkDeleted
3   ...
4 end
5
6 class Invoice < ActiveRecord::Base
7   before_destroy MarkDeleted
8   ...
9 end

9.2.7.1 Multiple Callback Methods in One Class

There’s no rule that says you can’t have more than one callback method in a callback class. For example, you might have special audit log requirements to implement:

 1 class Auditor
 2   def initialize(audit_log)
 3     @audit_log = audit_log
 4   end
 5
 6   def after_create(model)
 7     @audit_log.created(model.inspect)
 8   end
 9
10   def after_update(model)
11     @audit_log.updated(model.inspect)
12   end
13
14   def after_destroy(model)
15     @audit_log.destroyed(model.inspect)
16   end
17 end

To add audit logging to an Active Record class, you would do the following:

1 class Account < ActiveRecord::Base
2   after_create Auditor.new(DEFAULT_AUDIT_LOG)
3   after_update Auditor.new(DEFAULT_AUDIT_LOG)
4   after_destroy Auditor.new(DEFAULT_AUDIT_LOG)
5   ...
6 end

Wow, that’s ugly, having to add three Auditors on three lines. We could extract a local variable called auditor, but it would still be repetitive. This might be an opportunity to take advantage of Ruby’s open classes, allowing you to modify classes that aren’t part of your application.

Wouldn’t it be better to simply say acts_as_audited at the top of the model that needs auditing? We can quickly add it to the ActiveRecord::Base class so that it’s available for all our models.

On my projects, the file where “quick and dirty” code like the method in Listing 9.1 would reside is lib/core_ext/active_record_base.rb, but you can put it anywhere you want. You could even make it a plugin.

Listing 9.1 A Quick-and-Dirty acts_as_audited Method


1 class ActiveRecord::Base
2   def self.acts_as_audited(audit_log=DEFAULT_AUDIT_LOG)
3     auditor = Auditor.new(audit_log)
4     after_create auditor
5     after_update auditor
6     after_destroy auditor
7   end
8 end

Now the top of Account is a lot less cluttered:


1 class Account < ActiveRecord::Base
2   acts_as_audited

9.2.7.2 Testability

When you add callback methods to a model class, you pretty much have to test that they’re functioning correctly in conjunction with the model to which they are added. That may or may not be a problem. In contrast, callback classes are easy to test in isolation.


 1 describe '#after_create' do
 2   let(:auditable) { double() }
 3   let(:log) { double() }
 4   let(:content) { 'foo' }
 5
 6   it 'audits a model was created' do
 7     expect(auditable).to receive(:inspect).and_return(content)
 8     expect(log).to receive(:created).and_return(content)
 9     Auditor.new(log).after_create(auditable)
10   end
11 end
  • + Share This
  • 🔖 Save To Your Account