Observers Gem Extraction [Rails 4 Countdown to 2013]

Posted on

This post is part of a series of 31 Rails 4 articles being released each day in December 2012.

One of the biggest changes coming in Rails 4 is the extraction of certain features and moving them to gems. Moving forward, Active Record observers and Action Controller sweepers are going to be available in the rails-observer gem.

Rationale for Removal

With the removal of page and action caching from the core framework, the need for Action Controller cache sweepers is non-existent. Many Rails developers utilized cache sweepers to expire page/action caches when a specified Active Record model was saved, updated, or deleted.

In regards to Active Record observers, Rails developers have a love/hate relationship with them. While they provide an easy way to latch onto certain persistence operations, they usually end up as a dumping ground for concerns which are not persistence related.

Upgrade Path

If you are dependent on Active Record observers or Action Controller sweepers in your codebase, add the rails-observer gem to your Gemfile to ensure a seamless upgrade.

However, my personal recommendation would be to use callbacks where applicable within your models for persistence related concerns. Extract everything else to classes with a single responsibility and call them from your controllers. For example, if a new user signed up to your application, you could encapsulate all the logic for non-persistence related actions into a class UserSignup.

002

This post is by Kevin Faustino. Kevin is the Chief Craftsman of Remarkable Labs and also the founder of the Toronto Ruby Brigade.


Comments

comments powered by Disqus