Rails Tutorial: Short Circuit Assessment in Section 8.4.4

I gather in circles with a bit of code in section 8.4.4 (“Two subtle mistakes”) in the third edition of the Michael Hartl Rails tutorial. (Link to this section of the text: https://www.railstutorial.org/book/log_in_log_out#sec-two_subtle_bugs[1] )

In particular, I got confused in the following text / code:

"The second subtlety is that the user can log in (and remember) in several browsers, such as Chrome and Firefox, which cause a problem if the user logs out in one browser, but not Others. For example, suppose the user exits to Firefox, thereby setting the memory digest to nil (via user.forget in Listing 8.38). This will still work in Firefox because the log_out method in Listing 8.39 removes the user ID, so the user variable will be zero 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 a short circuit rating.

For this question, let's stick with Firefox and not worry about the second browser error. Hartley seems to be saying the following:

  • The log_out method sets digest to nil in the database.
  • log_out user_id, .
  • current_user , " current_user". user && user.authenticated?(cookies[:remember_token]).

- . log_out , elsif (user_id = cookies.signed[:user_id]) ? elsif , . current_user , . .

, , ?

+4
2

, ,

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

, ​​ IN FIREFOX., cookie Session 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, .

+1

( 2015 ), , , , .

0

All Articles