jjzjj

ruby-on-rails - railstutorial.org 中的 SessionsHelper : Should helpers be general-purpose modules for code not needed in views?

coder 2025-05-01 原文

railstutorial.org 有一个让我觉得有点奇怪的建议。

It suggests this code :

class ApplicationController < ActionController::Base 
  protect_from_forgery 
  include SessionsHelper 
end 

include SessionsHelper 使方法在 ApplicationController 中可用,是的,但它也使它们在任何 View 中都可用。我知道身份验证/授权是交叉的,但这真的是最好的地方吗?

在我看来,这可能范围太广了。将实现有条件重定向(如 railstutorial.org 示例所做的)的 before_filter 的代码放在更通常包含 View 助手的模块中似乎令人惊讶。

将 View 中不需要的功能放在 ApplicationController 或其他地方会更好吗?

还是我想太多了?

最佳答案

的确,你的感觉是对的。

我会以相反的方式实现:将函数 sign_incurrent_user 添加到 ApplicationController (或者如果你真的想:在在 lib 中定义一个单独的模块并包含它),然后确保 current_user 方法在 View 中可用。

简而言之:

class ApplicationController

  helper_method :current_user

  def sign_in

  end

  def current_user
    @current_user ||= user_from_remember_token
  end
end

当然,如果您要将大量代码放入 ApplicationController 中,它可能会变得困惑。在这种情况下,我会创建一个文件 lib\session_management.rb:

module SessionManagement
  def self.included(base)
    base.helper_method :current_user
  end

  def sign_in
    ..
  end

  def current_user
    ..
  end
end

然后在你的 Controller 中你可以写:

class ApplicationController
  include SessionManagement
end

关于ruby-on-rails - railstutorial.org 中的 SessionsHelper : Should helpers be general-purpose modules for code not needed in views?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5500322/

有关ruby-on-rails - railstutorial.org 中的 SessionsHelper : Should helpers be general-purpose modules for code not needed in views?的更多相关文章

随机推荐