As of Rails 2.3, there is a handy new
trymethod on objects, which allows you to invoke a method on a possibly
nilobject without throwing a
NoMethodError. This saves you the trouble of checking if your object is
nilbefore 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
tryyou can skip the
nil?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”.