samedi 25 juillet 2015

Session Helper Methods in Michael Hartl Tutorial Chapter 8

I'm going through Michael Hartl tutorial on Ruby on Rails and I'm having trouble understanding some logic. Note that the logic works, it's just not resonating with me on what's actually happening.

In this chapter we're logging in users and creating a session. Here the helper methods:

module SessionsHelper
    # Logs in the given user.
    def log_in(user)
      session[:user_id] = user.id
    end

    # Returns the current logged-in user (if any).
    def current_user
      @current_user ||= User.find_by(id: session[:user_id])
    end

    # Returns true if the user is logged in, false otherwise.
    def logged_in?
      !current_user.nil?
    end
end

Depending on whether the user's logged on or not we change the navigation with this conditional:

<% if logged_in? %>
   do something....
<% else %>
   do something else...
<% end %>

As I understand it, the code checks to see if the user is logged in by calling the logged_in? method. The logged_in? method calls the current_user method to see if it's nil. If it is nil it returns false, if it's not nil it returns true. As a test I tried to change the logged_in? method to the following:

def logged_in?
  !@current_user.nil?
end

Doesn't the current_user method set the @current_user instance variable to the user where User.id = session[:user_id] if @current_user is nil? If that's correct why wouldn't the way I modified the logged_in? method work? @current_user would either be equal to nil or there would be a user object associated so it would be evaluated to true, right? Am I incorrect in how this is evaluated (or returned)?

Aucun commentaire:

Enregistrer un commentaire