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?

+3


source to share


5 answers


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.

+7


source


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.

+2


source


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

+2


source


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.

+2


source


This function returns a string with the email address and whether it is an administrator or a user ... i.e.

user_1 = {:email => "test@email.com", :admin => true}

      

so call

user_1.to_s 

      

will return a string

"test@email.com Admin"

      

+1


source







All Articles