.try
This Ruby method returns nil rather than raising an exception when called on a non-existent object.
Here’s a practical example: Is the currently signed in user an admin? If so, he should see site admin links, otherwise they should be hidden:
any_view_file.html.erb:
The above code breaks when the page is viewed by a non-signed-in visitor and current_user
is not set (i.e. is nil).
The if
statement can be augmented to include two tests:
Or the try
method can be used to clean up the code:
The if
statement will return true
if the currently signed in user is an admin, false
if he is not, and nil
if there is no signed in user. Since nil
is falsey, the admin links remain nicely hidden.
(This approach merely cleans up the layout for unauthorized users. It should not be relied on to actually prevent unauthorized access to controller actions.)