1

I'm following railstutorial by Michael Hartl. In chapter 8.2.2 he defines a variable @current_user and a method current_user.

app/helpers/sessions_helper.rb looks like this:

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

end

Hartl defines @current_user an instance variable (of User object I guess); How can @current_user be an instance variable if it is itself an instance of the User class?

0

2 Answers 2

2

This is such a good question. It seems that this arrangement is not something that it was planned for, it simply happened: u need to have a variable that has some kind of memory outside the method (scope), in order to compare if @current_user=@current_user, but at the same time the whole arrangement makes theoretically no sense.

This article was written in 2008 and was proof read from members of the rails core team. This paragraph is very telling of the situation:

http://www.railway.at/articles/2008/09/20/a-guide-to-memoization/

--> "A little note on naming here: Some people seem to prefer prefixing the memoizing variable’s name with an underscore to indicate that it’s not meant to be used as an actual instance variable. To be honest, I don’t think this is really necessary unless you define a whole bunch of instance variables and memoized variables."

Sign up to request clarification or add additional context in comments.

Comments

1

The SessionsHelper module is mixed into your controllers, so @current_user will be set as an instance variable of the controller which is handling the current request (Rails creates a new controller instance to handle each request)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.