Modularizing filters to use with many models?

11 views
Skip to first unread message

Carson Cole

unread,
Nov 11, 2011, 5:12:22 PM11/11/11
to rubyonra...@googlegroups.com
How could one modularlize a group of filters to be used in many models? I like to avoid this (again, I am doing this in many models):

class Something
  before_filter :a
  before_filter :b
  after_filter :c
end


and instead, just be able to do this (something like it)

class Something
  ....
end


Is this solvable through inheritance?


Carson Cole

unread,
Nov 11, 2011, 5:21:40 PM11/11/11
to rubyonra...@googlegroups.com
Meant to save callback instead of filter.

Frederick Cheung

unread,
Nov 12, 2011, 7:26:08 AM11/12/11
to Ruby on Rails: Talk
So, you could have an abstract base class, but obviously doesn't help
if you have multiple sets of callbacks, filters etc and models need to
be able to mix and match at will

A more flexible way, using modules is

module MyCallbackPackage
extend ActiveSupport::Concern
included do
before_filter :a
before_filter :b
end

def a
end
def b
end
end

then you can do

class MyController < ActionController::Base
include MyCallbackPackage
end

The ActiveSupport::Concern gives you the included method and makes
that side of things more convenient. You don't need to use it - you
can achieve it all through self.included

Fred

Carson Cole

unread,
Nov 12, 2011, 1:09:55 PM11/12/11
to rubyonra...@googlegroups.com
Fred,
Thank you so much for the reply, and it was a great one. Did not know about that and you broadened my knowledge of extend vs. include and included. I had only been using modules to extend instance methods, but this opened up a new world. From your answer, I was able to remove 5 lines of code from 12 models and can now manage the function from just one location (rather than having to fix 5 lines X 12 models--tedious!). 

Honored to have you respond, since I know that you have given many, many hours to responses over the years, and they have always been top quality and educational. How about writing a good Ruby book with some Rails 3.1 goodness? You can call it "Fred's Ruby Tips & Tricks".  I'd buy it.

Carson Cole
Reply all
Reply to author
Forward
0 new messages