放置多个控制器之间共享的before_filter的位置 [英] Where to put a before_filter shared between multiple controllers
问题描述
我有多个控制器,它们都使用相同的before_filter.为了保持干燥,该方法应该放在哪里,以便所有控制器都可以使用它?尽管我不确定为什么,但模块似乎不是正确的地方.我不能将其放在基类中,因为控制器已经具有不同的超类.
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.
推荐答案
如何将before_filter和方法放在模块中并将其包含在每个控制器中.我将此文件放在lib文件夹中.
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
最后,我将确保自动加载lib.打开config/application.rb并将以下内容添加到您的应用程序的类中.
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)
这篇关于放置多个控制器之间共享的before_filter的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!