Lee Eather Lee Eather - 24 days ago 10
Ruby Question

Distinguishing between User and user in rails when getting a user from the database

This is my sessions controller. I changed a line of code in this question and I am just a bit uncertain why it is the way it is.

I have looked in to the definition of classes and done alot of researching trying to find out why

unless user.present?
is not a capital U. E.g.
unless User.present?


If it is of the User class then it should be User to be searched for in the database as
User.find_by
is.

Does rails first look into the database that reads User as user, lowercase.

I say this because the line of code before it also uses
user = User.from_omniauth(env["omniauth.auth"])
and User is also capitalised, so how can rails distinguish between the twolines of code that are both of the User class?

def create
user = User.from_omniauth(env["omniauth.auth"])

unless user.present?
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in user
redirect_to user_url(user)
# Log the user in and redirect to the user's show page.
else
# Create an error message.
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
else
log_in user
redirect_to user_url(user)
end
end

Answer

When you write:

user = User.from_omniauth(env["omniauth.auth"])

you are defining a variable user, which is used later on in your controller.

So, when you then write:

unless user.present?

You are really writing:

unless User.from_omniauth(env["omniauth.auth"]).present?

The line User.from_omniauth(env["omniauth.auth"]) is getting the User from the database, storing it inside the user variable, and checking whether a User is present

Also, in your unless statement, you are defining a user variable so it can be used in a different manner than the original user variable in line 2

Capitalisation in ruby (and most languages) will mean different things. For example, if you had 3 variables: User, user and USER they are all different. Ruby can distinguish between the three, just like in your method.