Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 806
Undistraction Avatar asked Aug 13 '12 18:08

Undistraction


2 Answers

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)
like image 82
nwwatson Avatar answered Sep 25 '22 01:09

nwwatson


Something like this can be done.

Class CommonController < ApplicationController
  # before_filter goes here
end

Class MyController < CommonController
end

class MyOtherController < CommonController
end
like image 44
Kulbir Saini Avatar answered Sep 23 '22 01:09

Kulbir Saini