Can someone explain the following code to me?
I am following along with Rails 3 in an action book and it is about overriding to_s
in a model. The code is as follows:
def to_s
"#{email} (#{admin? ? "Admin" : "User"})"
end
I know that in Ruby you can display a value inside double quotes "#{value}"
, but what about double question marks?
source to share
This is string interpolation . "#{email} (#{admin? ? "Admin" : "User"})"
equivalent to
email.to_s + " (" + (admin? ? "Admin" : "User") + ")"
i.e
email.to_s + " (" + if admin? then "Admin" else "User" end + ")"
This results in quotation marks in this context Admin
and User
are used as strings and not as constants.
source to share
The first question mark is on rails attribute query methods. http://api.rubyonrails.org/classes/ActiveRecord/Base.html#label-Attribute+query+methods
(unless you have overwritten / overridden this method)
This is a shorthand method to see if this attribute is present or not.
source to share
Really an admin? it is a function (possibly defined somewhere in a method or controller / helper model) that return a boolean value (true or false) and the next question mark as an if condition
if admin? == true
"Admin"
else
"User"
the first part before ":" is for true case and the other is for false case
source to share
Don't think of it as a double question mark, the first question mark is part of the method name (Ruby allows method names to end with "!", "?", "=", "[]", Etc.). Since admin is a boolean ActiveRecord, add an admin? a method that returns true if the user is an administrator, otherwise false.
Another question mark is used with a colon (:) and you can see it as:
condition ? statement_1 : statement_2
If the condition is true, the first statement is executed and the second is evaluated.
So, put these two things together and you have a concatenation of strings that add the word "Admin" or "User" between the brackets.
source to share