jeff gardner.

Adding ActiveRecord-style callbacks to ActiveResource models

I’ve recently been working on a web app that is completely backed by ActiveResource. In fact, the web app doesn’t even have it’s own database. Thankfully the API that I’m pulling data from is fairly REST architectured which allows me to use ActiveResource to handle most of my models. My beef in the past has always been that ActiveResource has been treated like the red-headed step-child of the Rails stack, left mostly to drag it’s feet along behind the rest of the framework, missing some of the more important and life-simplifying bits that are a part of ActiveRecord.

Decoupled architecture

In Rails 3 some of this has been addressed. Before Rails 3 you couldn’t even validate records locally before making calls to the API, that’s changed and by default now you can just call validates_presence_of :name and any of the other validations you’re used to using with ActiveRecord models. Much nicer, much more Rails-like.

One thing that is not default in ActiveResource models is the ability to use callbacks. I like callbacks, I use them all the time to take care of all sorts of functionality that needs to happen behind the scenes. Callbacks make it much easier for me to make the user’s experience much easier and I like that. So why was it left out of the defaults? Who knows.

Thankfully, the Rails gods have been kind. Rails 3 went a long way towards completely decoupling the framework into different modules that make it easy to include only the functionality you need, when you need it.

Adding callbacks to ActiveResource

Callbacks (and validations for that matter) is now a module that lives in ActiveModel. This is great because it means that we can include the callbacks module with one simple line extend ActiveModel::Callbacks.

This simply includes the callback module. But we’re not done yet. We need to define which callbacks we’d like to use. We can pass any of the callbacks you’re used to using in ActiveRecord here: :save, :create, :update are all options.

You can see that I’m only interested in the callbacks that are associated with the save action. So by including this I’m given access to the before_save method, the after_save method and the around_save method. Pretty hott huh? Yeah, double t hot!

From that point you can just continue like you were working with an ActiveRecord model. Add callbacks and callback methods to your heart’s content. For more info about ActiveModel check out this great post by Yehuda Katz. And for the super detailed nerd version about ActiveModel callbacks check the docs here.


Tagged: Ruby on Rails 3.0, ActiveRecord, ActiveResource, and callbacks
26 May 2011

blog comments powered by Disqus