Give it a try!
As of Rails 2.3, there is a handy new
try
method on objects, which allows you to invoke a method on a possiblynil
object without throwing aNoMethodError
. This saves you the trouble of checking if your object isnil
before accessing a method.For example, previously you’d need to do something like this:
article = Article.find_by_title("My Article") unless article.nil? article.body end
With
try
you can skip thenil?
check and do the following:Article.find_by_title("My Article").try(:body) => #body or nil
Check out the documentation on try.
This post was ‘manually’ reblogged from michaelbulat.
Checking for NPEs can be a real p.i.t.a., that’s one nice feature!
Here’s a post on this subject with a “DIY implementation”.