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)
  def my_before_filter

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

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

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



Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s