在多个控制器之间共享before_filter的位置

Und*_*ion 12 ruby module before-filter ruby-on-rails-3

我有多个控制器都使用相同的before_filter.为了保持干燥,这种方法应该放在哪里,以便所有控制器都可以使用它?一个模块似乎不是正确的地方,虽然我不知道为什么.我不能把它放在基类中,因为控制器已经有不同的超类.

nww*_*son 28

如何将您的before_filter和方法放在模块中并将其包含在每个控制器中.我把这个文件放在lib文件夹中.

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
Run Code Online (Sandbox Code Playgroud)

然后在你的控制器中,你所要做的就是

class MyController < ActionController::Base
  include MyFunctions
end
Run Code Online (Sandbox Code Playgroud)

最后,我会确保lib是自动加载的.打开config/application.rb并将以下内容添加到应用程序的类中.

config.autoload_paths += %W(#{config.root}/lib)
Run Code Online (Sandbox Code Playgroud)

  • 如果它不是公开面对的话,不要忘记在模块中使用过滤器方法`protected`. (3认同)