Preserve Semantics in Callbacks

Many people tend to place logic within a method named for the callback (e.g. after_destroy).  This works fine, but tends to be less maintainable, in my opinion.

You basically have a method called after_destroy (or whatever), but you don’t readily know what its doing.  A better approach is to write an intention-revealing named method and reference that in the reference to your callback method.  You then can see through the method name what is happening in response to the event.  Further, the method can be used at other times.  This approach restores a bit of maintainability to your code.

I have included an example of this approach below.  You’ll have to visualize the before version — I don’t like posting less maintainable code because sometimes people skim it without reading and take it as good code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Rating < ActiveRecord::Base
  
  # ---- Associations ----
  
  # The rateable that was rated.
  belongs_to :rateable
  
  
  # ---- Callbacks ----
  
  after_destroy :update_ratings
  
  
  # ---- Calculations ----
  
  # Updates the parent's rating count and average rating.
  def update_ratings
    rateable.update_ratings
  end
end
This entry was posted in Ruby, Ruby on Rails. Bookmark the permalink.

One Response to Preserve Semantics in Callbacks

  1. Well, I apologize for this post not being such a new idea. I just found this:

    http://therailsway.com/2007/6/7/railsconf-recap-named-callbacks

    which I may have read previously and been inspired by, but couldn’t remember.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>