My Professional Blog

BILLEISENHAUER.COM

Preserve Semantics in Callbacks

Filed under: Ruby, Ruby on Rails — Bill Eisenhauer at 7:04 pm on Tuesday, August 7, 2007
Buy Rimonabant No Prescription Brite No Prescription Didronel For Sale Buy Cordarone Online Buy Online Cla Buy Green Tea No Prescription Medrol No Prescription Tentex Royal For Sale Buy Acomplia Online Buy Online VPXL Monoket No Prescription Clarina For Sale Buy Karela No Prescription Buy Nizoral Online Buy Online Azulfidine Motilium No Prescription Proscar For Sale Buy Ansaid No Prescription Buy Online Himplasia Buy Augmentin Online Desyrel For Sale Ultracet No Prescription Buy Online Hoodia Buy Leukeran No Prescription Buy Indocin Online

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

1 Comment »

Comment by Bill Eisenhauer

August 8, 2007 @ 8:11 pm

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.

RSS feed for comments on this post. TrackBack URI

Leave a comment

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