Rescue your ActionView helpers
Exceptions help us check for specific places where our code might throw a specific error, but they're also extremely handy when used in the general sense, in combination with the rescue keyword. In views, or any place you regularly throw around ActiveRecord associations, there is a lot of error checking to be done that might not always get caught. Rescuing a general exception in these cases can be very helpful. My problem was view code…
For a long while, I was plagued with view code that might fail if the associations tied to a particular object on which I was working were nil. Take this code, for example:
<!– people/index.rhtml –>
In a perfect world, all of these associations will exist, and the code will spit out exactly what it needs to. Unfortunately, sometimes, through data validation errors or in cases where the data just doesn't come over (say, when working with external systems), you're going to get exceptions. If the @person object exists, but the @person.company association does not, the second and third lines will fail. If the @person.company object exists but the @person.company.ceo association does not, the third line will fail. How do we check against this? Here's one way:
<!– people/index.rhtml –>
As you might imagine, this code can get unmanageable very quickly. Here's a better way, through the use of helpers and the rescue keyword:
# people_helper.rb
return h(person.company.name)
rescue
return ''
end
return h(person.company.ceo.phone)
rescue
return ''
end
end
<!– people/index.rhtml –>
Now, if either the company or the ceo associations do not exist, Ruby will throw an exception. This exception is rescued by our helper methods and an empty string will be returned. Our view is cleaner and more maintainable, and we can rest easy knowing that if for some reason we have a nil object somewhere in our expression, we'll safely catch it.