Great Rails Feature #1: ActiveRecord Callbacks
Thursday December 22, 2005 / 7 CommentsNow that I’m spending more time with Rails, I thought it would be fun to document some of the wonderful features that make it so elegant. Today, it’s Active Record Callbacks. Of all it’s strengths, Rails does a particularly elegant job with the MVC convention. The implementation of callbacks is on thing I really appreciate. What are callbacks, you ask?
Callbacks are hooks into the lifecycle of an Active Record object that allows you to trigger logic before or after an alteration of the object state.
So, say for instance, you always want to perform a certain action anytime a record is updated or created, you simply reference before_save with a particular function call in the model, and that function will be called everytime an instance of that model is created or updated.
class Entry < ActiveRecord::Base
before_save :populate_html_description
def populate_html_description
r = RedCloth.new self.description_textile
self.description = r.to_html
end
end
Now, everytime I save an entry, it automatically parses the text with Textile and saves an HTML version at the same time. This way, I don’t have to create the HTML version for every request. And best of all, that’s a couple more lines of code put where they belong: in the model. I don’t need to include that logic in my controller, and it’s simpler for it.
Another powerful callback is before_destroy. If you have a record that also references a set of associated files that are stored somewhere else, you could make sure those files get cleaned up as well.
Of course, these are simple examples. There are 16 different callbacks in total, and if taken advantage of, they can really help you create more elegant code and keep it where it belongs. For more information, check out the rereference on ActiveRecord Callbacks.
Featured Stuff - Resources: Wireframes & Page Description Diagrames
Omnigraffle and Visio versions of the wireframe templates and stencils I use on all of my projects. There’s even a few examples included for good measure. More about Wireframe & Page Description Diagram Stencils and Templates
Yes, I find callbacks a way of creating a neat looking code. They are delicious! ;)
Piotr UsewiczHave a look at Og, an even more advanced Ruby ORM library. Instead of a custom hack like callbacks, Og uses a generalize AOP system. Check out some videos here:
www.nitrohq.com/view/Videos
George MoschovitisCallbacks are sweet, but I’m not so sure the example is my cup of tea.
Saving text in a formatted state limits you to the formatting engine from there on out and also binds the text to a certain display format (HTML). Of course, formatting the text at display time also has it’s disadvantages :)
Justin PerkinsJustin:
You missed a tiny important bit in that the code doesn’t permanently alter the source data (the description). As can be seen in the code above, he’s taking the description from the _description_textile_ property and, after transforming that, moving it to the description property/column mapping.
This could be looked at as a pseudo- or full-fledged- moimization!
I personally find callbacks to be a godsend.
M.T.
Matt ToddGeorge, no offence, but half the time your nitro site is down. Not exactly exciting when you’re trying to compete with the hottest kid on the block.
gratefulJustin,
description_textile (a.k.a the original input) is still available, and I’m sure that’s stored in the DB as well. If the view layer changes so drastically from HTML (which, you have to admit, is probably unlikely) you can retranslate the original input to whatever new output view you’d like to use.
Jim Van FleetPoints well taken guys, sometimes I’m so picky I trip myself.
One thing that might help, activerecord callback methods should probably be protected so they cannot be called by controllers and such.
Justin PerkinsComments are closed for this entry.