我有多个 Controller ,它们都使用相同的 before_filter。为了让事情保持干燥,这个方法应该放在哪里以便所有 Controller 都可以使用它?模块似乎不是正确的位置,但我不确定为什么。我不能将它放在基类中,因为 Controller 已经有不同的父类(super class)。
最佳答案
如何将您的 before_filter 和方法放在一个模块中,并将其包含在每个 Controller 中。我会将此文件放在 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
然后在你的 Controller 中,你所要做的就是
class MyController < ActionController::Base
include MyFunctions
end
最后,我会确保 lib 是自动加载的。打开 config/application.rb 并将以下内容添加到您的应用程序的类中。
config.autoload_paths += %W(#{config.root}/lib)
关于ruby - 多个 Controller 之间共享的 before_filter 放在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11940253/