What's New in Edge Rails: Object.try
This feature is scheduled for: Rails v2.3/3.0
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:
1 2 3 4 5 |
# 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
tags: ruby,
rubyonrails


Recent comments
1 year 23 weeks ago
1 year 23 weeks ago
1 year 25 weeks ago
1 year 27 weeks ago
1 year 42 weeks ago
1 year 45 weeks ago
1 year 45 weeks ago
1 year 45 weeks ago
1 year 46 weeks ago
1 year 48 weeks ago