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.
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)
Something like this can be done.
Class CommonController < ApplicationController
# before_filter goes here
end
Class MyController < CommonController
end
class MyOtherController < CommonController
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With