ActiveRecord callback names should be expressive
ActiveRecord provides a bunch of useful callbacks which will be run at various stages during the lifecycle of an ActiveRecord object. There are lots of ways to define these callbacks, and the easiest way is something like this.
class Widget < ActiveRecord::Base
def after_save
# What did this code do again?
end
end
Seems harmless enough, right? Sure, as long as you're writing a throwaway prototype. Try adding another after_save
callback, or implementing the callback in a subclass. Try coming back to the callback after 6 months and trying to work out what it's meant to be doing. That way insanity lies.
Name your callbacks expressively and you'll reap the immediate benefits of more readable code and easier implementation. You'll also have a decent indication - the method name - of what the callback was meant to do when you come back to the code in 6 months.
class Widget < ActiveRecord::Base
after_save :add_widget_to_bill_of_materials
def add_widget_to_bill_of_materials
# No need to guess what this method does,
# it's right there in the name!
end
end
curl -LO http://barkingiguana.com/2008/12/01/activerecord-callback-names-should-be-expressive.html.orig
curl -LO http://barkingiguana.com/2008/12/01/activerecord-callback-names-should-be-expressive.html.orig.asc
gpg --verify activerecord-callback-names-should-be-expressive.html.orig{.asc,}
If you'd like to have a conversation about this post, email craig@barkingiguana.com. I don't bite.