加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails教程:8.4.4节中的短路评估

发布时间:2020-12-17 02:07:21 所属栏目:百科 来源:网络整理
导读:在Michael Hartl的Rails教程的第3版中,我将在第8.4.4节(“两个微妙的错误”)中加入一些代码. (链接到本节的这一部分: https://www.railstutorial.org/book/log_in_log_out#sec-two_subtle_bugs[1]) 具体来说,我对以下文本/代码感到困惑: “The second subt
在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而不用担心第二个浏览器错误.哈特尔似乎在说以下内容:

> log_out方法将记忆摘要设置为数据库中的nil.
> log_out方法删除存储在会话中的user_id
和饼干.
>从同一浏览器中对current_user方法的后续调用不会引发错误,因为“current_user方法中的用户变量将为nil”.这将导致表达用户&& amp;的短路. user.authenticated(饼干[:remember_token])?

我的问题是如何发生这种情况.如果log_out方法按照规定工作,那么在后续调用中,elsif(user_id = cookies.signed [:user_id])行不应该为false吗? elsif块不会运行,用户变量永远不会被设置.实际上,current_user方法中的两个条件都是false,并且该方法将返回nil.根据用户变量不会出现短路.

他描述的短路评估可以进行吗?

解决方法

你是对的,因为没有发生短路

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

不运行,用户变量永远不会设置为IN FIREFOX.,因为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登录,这是发生错误的地方.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读