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

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

如何将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 

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

 class MyController < ActionController::Base include MyFunctions end 

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

 config.autoload_paths += %W(#{config.root}/lib) 

这样的事情可以做到。

 Class CommonController < ApplicationController # before_filter goes here end Class MyController < CommonController end class MyOtherController < CommonController end 

before_filter放在控制器的共享超类中。 如果你必须走得很远,那么这就是ApplicationController的inheritance链,并且你被迫将before_filter应用于它不应该应用的某些控制器,你应该在那些特定的控制器中使用skip_before_filter

 class ApplicationController < ActionController::Base before_filter :require_user end # Login controller shouldn't require a user class LoginController < ApplicationController skip_before_filter :require_user end # Posts requires a user class PostsController < ApplicationController end # Comments requires a user class CommentsController < ApplicationController end 

如果它对所有控制器都是通用的,您可以将它放在应用程序控制器中。 如果没有,您可以创建一个新控制器并使其成为所有控制器的超类,并将代码放入其中。