try(), try() again in Rails

April 28, 2011

In Rails, try() lets you call methods on an object without having to worry about the possibility of that object being nil and thus raising an exception. I know I sometimes forget about it, and I’ve looked at enough code from other developers to know that I’m not the only one. So today I’d like to give you a brief introduction to the method (and hopefully ingrain it a little deeper into my own brain). Let’s look at some very simple code from a Rails view.

**Disclaimer:** While handy, this technique is not a replacement for good techniques like validations and default database values. Don't get lazy.


Here’s a simple example of code you might replace with try(). Say you’ve got a (rather contrived) Product model in your project. A Product may or may not have a known manufacturer, and some links you only want to display if a user is logged in and has administrator rights:

  <!-- products/show.html.erb (before) -->
  <h1><%= %></h1>

  <% unless @product.manufacturer.nil? %>
    <%= %>
  <% end %>

  <% if current_user && current_user.is_admin? %>
    <%= link_to 'Edit', edit_product_path(@product) %>
  <% end %>

Like I said, it’s contrived, but it should give you the idea. try() can help us in a couple of places here:

  <!-- products/show.html.erb (after) -->
  <h1><%= %></h1>

  <%= @product.manufacturer.try(:name) %>

  <% if current_user.try(:is_admin?) %>
    <%= link_to 'Edit', edit_product_path(@product) %>
  <% end %>

With arguments and blocks

You can pass arguments and blocks to try():

  > @manufacturer.products.first.try(:enough_in_stock?, 32)
  # => "Yes"
  > @manufacturer.products.try(:collect) { |p| }
  # => ["3DS", "Wii"]


You can chain multiple try() methods together. In another contrived example, say you’ve got a method in your Manufacturer model that sends the manufacturer a message whenever called.

  class Manufacturer < ActiveRecord::Base
    has_many  :products

    def contact
      "Manufacturer has been contacted."

  #=> nil 
  #=> "Manufacturer has been contacted."

Further reading

You can start with the Rails docs on try(). Rails’ inclusion of try() was inspired by Chris Wanstrath’s post about adding try() to Ruby. Raymond Law at Intridea has a clever way to chain multiple calls to try(). And Scott Harvey has shared a more practical example of try().

Rails testing made simple

Learn to test Rails apps the way I learned, building up tests step-by-step, in Everyday Rails Testing with RSpec. Expanded to include exclusive content and a complete sample Rails application. Learn more »

blog comments powered by Disqus