Adding a Ruby module containing filters to Rails Models

I recently encountered this scenario where a few models in my rails app had to have the same before_save and after_save filters. To maintain the DRYness of the code, the obvious thing to do was put those methods in a module and just include that module in the model classes where I needed those filters. But since filters are defined on the class, I had to add an extra method to do this:

module ModuleContainingFilters
  def self.included(base)
    base.before_filter(:my_before_filter)
  end
  def my_before_filter
    ....
  end
end

And in the models, all you need to do is:

class MyModelM1 < ActiveRecord::Base
  include ModuleContainingFilters
  before_filter :another_before_filter1, :another_before_filter2
  ..
  ..
end

which will add my_before_filter as well as other before filters which you could have defined.

References: http://blog.jayfields.com/2006/12/ruby-instance-and-class-methods-from.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s