12

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

4

4 回答 4

30

如何将你的 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)
于 2012-08-14T13:47:25.043 回答
4

可以做这样的事情。

Class CommonController < ApplicationController
  # before_filter goes here
end

Class MyController < CommonController
end

class MyOtherController < CommonController
end
于 2012-08-13T18:39:56.853 回答
3

before_filter放在控制器的共享超类中。如果您必须在继承链上走这么远,这最终成为ApplicationController,并且您被迫将其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
于 2012-08-13T18:42:32.567 回答
1

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

于 2012-08-13T18:38:06.873 回答