gpt4 book ai didi

ruby-on-rails - Rails 教程 : Short-Circuit Evaluation in section 8. 4.4

转载 作者:行者123 更新时间:2023-12-01 05:08:28 25 4
gpt4 key购买 nike

我将在 Michael Hartl 的 Rails 教程第 3 版的第 8.4.4 节(“两个微妙的错误”)中编写一些代码。 (链接到此部分文本:https://www.railstutorial.org/book/log_in_log_out#sec-two_subtle_bugs[1])

具体来说,我对以下文本/代码感到困惑:

"The second subtlety is that a user could be logged in (and remembered) in multiple browsers, such as Chrome and Firefox, which causes a problem if the user logs out in one browser but not the other. For example, suppose that the user logs out in Firefox, thereby setting the remember digest to nil (via user.forget in Listing 8.38). This would still work in Firefox, because the log_out method in Listing 8.39 deletes the user’s id, so the user variable would be nil in the current_user method:


def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(cookies[:remember_token])
log_in user
@current_user = user
end
end
end

As a result, the expression

user && user.authenticated?(cookies[:remember_token])

returns false due to short-circuit evaluation."



对于这个问题,让我们坚持使用Firefox,而不用担心第二个浏览器错误。 Hartl 似乎在说以下内容:
  • log_out 方法将数据库中的内存摘要设置为 nil。
  • log_out 方法删除两个 session 中存储的 user_id
    和 cookies 。
  • 从同一浏览器中对 current_user 方法的后续调用不会引发错误,因为“用户变量在 current_user 方法中将为 nil”。这会导致表达式 user && user.authenticated?(cookies[:remember_token]) 短路.

  • 我的问题是这怎么可能发生。如果 log_out 方法按规定工作,那么行 elsif (user_id = cookies.signed[:user_id]) 不应该在随后的调用中是假的? elsif 块不会运行,并且永远不会设置用户变量。事实上,current_user 方法中的两个条件都是假的,并且该方法将返回 nil。不会有基于用户变量的短路。

    他描述的短路评估能发生吗?

    最佳答案

    您是正确的,因为短路不会发生

    elsif (user_id = cookies.signed[:user_id])



    不会运行并且永远不会设置用户变量 在火狐。 , 因为 cookie 在 Sessions Helper 中被删除:
    # Forgets a persistent session.
    def forget(user)
    user.forget
    cookies.delete(:user_id)
    cookies.delete(:remember_token)
    end

    # Logs out the current user.
    def log_out
    forget(current_user)
    session.delete(:user_id)
    @current_user = nil
    end

    然而,这并没有改变 Hartl 的主要观点,即用户也是通过 登录的。 Chrome ,这是发生错误的地方。

    关于ruby-on-rails - Rails 教程 : Short-Circuit Evaluation in section 8. 4.4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26738617/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com