Rails Devise gem
If the page could potentially not have a current_user set then:
if current_user.try(:admin?) # do something end
Ruby is somewhat unusual in that it lets you include a wide range of characters in the names of methods including
They have no special significance to the interpreter but the language convention is that:
?are interrogative - they should ALWAYS return true or false.
!either mutate the object the are called on or may raise a exception.
So why does it matter at all? In this particular case it does not matter since your user class has an accessor for the
admin instance variable created by ActiveRecord - just like any other column.
If it did not however
current_user.try(:admin) would always return nil. Remember that instance variables are always private in Ruby until you provide an accessor*.
class User def initialize @admin = true end def admin? @admin end end User.new.try(:admin) # is always nil...
This is because
User does not respond to
.try prevents a
NoMethodError and just returns nil instead.