.try

This Ruby method returns nil rather than raising an exception when called on a non-existent object.

$ rails console

2.1.0 :001 > nil.admin?
NoMethodError: undefined method 'admin?' for nil:NilClass
... stack trace ...

2.1.0 :002 > nil.try(:admin)
 => nil

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:

<% if current_user.admin? %>
  Show links
<% end %>

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:

<% if current_user && current_user.admin? %>
  Show links
<% end %>

Or the try method can be used to clean up the code:

<% if current_user.try(:admin) %>
  Show links
<% end %>

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 if nil evaluates to false, 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.)

Tagged ,

One thought on “.try

Leave a comment