Monday, December 8, 2008

Object.try

Those of you using Chris Wanstrath’s slick little try trick will now have access to that functionality in Rails with this ActiveSupport update.

Basically, try lets you attempt to invoke a method on an object without worrying about a NoMethodError being raised. If the method doesn’t exist, or if the target object nil, then nil will be returned without exceptions:

# No exceptions when receiver is nil
nil.try(:destroy) #=> nil

# Useful when chaining potential nil items
User.admins.first.try(:address).try(:reset)

Just a small little bit of syntactical candy pulled in from the community.

Update: You can now also use this trick for methods with arguments

http://ryandaigle.com/articles/2008/11/20/what-s-new-in-edge-rails-object-try

No comments: