简体   繁体   中英

From Rails Tutorial Ch8 - why is instance variable not used?

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

Currently working through Hartl's Rails Tutorial in Ch 8 where he gets you to write code for users to log in and stay logged in.

Under method logged_in?, why is local variable current_user used instead of @current_user ?

current_user is not a local variable, it's an instance method.

why is instance variable not used?

It is being used.

When you call current_user method it returns an instance variable @current_user , which happens to be either a User object or nil .

That isn't a local variable! He's calling the current_user method which returns the @current_user value and so chains nil off of it. You need to look into scope in ruby to see how methods and instance variables and local variables interact with one another!

Because current_user - is method defined in same module. This technique called memoization. You can read about here http://www.justinweiss.com/articles/4-simple-memoization-patterns-in-ruby-and-one-gem/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM