Search code examples
rubyruby-on-rails-3modulebefore-filter

Where to put a before_filter shared between multiple controllers


I have multiple controllers that all use an identical before_filter. In the interests of keeping things dry, where should this method live so that all the controllers can use it? A module doesn't seem like the right place, though I'm not sure why. I can't put it in a base class as the controllers already have different superclasses.


Solution

  • How about putting your before_filter and method in a module and including it in each of the controllers. I'd put this file in the lib folder.

    module MyFunctions
    
      def self.included(base)
        base.before_filter :my_before_filter
      end
    
      def my_before_filter
        Rails.logger.info "********** YEA I WAS CALLED ***************"
      end
    end
    

    Then in your controller, all you would have to do is

    class MyController < ActionController::Base
      include MyFunctions
    end
    

    Finally, I would ensure that lib is autoloaded. Open config/application.rb and add the following to the class for your application.

    config.autoload_paths += %W(#{config.root}/lib)