0

In this book: http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-users#code:current_user_p

The author does the following:

  def current_user
    @current_user ||= User.find_by_remember_token(cookies[:remember_token])
  end

  def current_user?(user)
    user == current_user
  end

my question is when there is a comparison, user == current_user; what is rails comparing? user == @current_user? or user.name == @current_user.name ?

What would hapen if I had the following

  def current_user
    @current_user ||= User.find_by_remember_token(cookies[:remember_token])
    @other_user ||= User.find_by_other_token(cookies[:other_token])
  end

would ser == current_user compare other_user?

2 Answers 2

2

The current_user in user == current_user is a call to the current_user method, and in ruby a method returns the last statement that is executed. So in the example, @current_user is being compared to user.

If you add @other_user to the current_user method, then you are correct in thinking that user == current_user would compare user to @other_user.

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

Comments

1

@current_user → the instance variable
current_user → the method

So the current_user? method compares the return value of current_user (the method) to the user argument.

Here's the exact same code, but with slightly different names:

def get_current_user
  @current_user ||= User.find_by_remember_token(cookies[:remember_token])
end

def is_current_user?(user)
  user == get_current_user
end

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.