Rails Try with Parameters
07 Jul 2010
When dealing with a collection of different objects in Rails, it is often necessary to call a method that may or may not be defined on all of the instances in the collection. For example, formatting the following array of DateTimes will throw an ArgumentError:
[1.day.ago, 1.day.from_now, nil].each {|d| puts d.to_s(:admin)}
The reason being that nil.to_s takes zero arguments.
Trying
Rails provides try, which can be used in association with a list of parameters to attempt to invoke a method on an object:
[1.day.ago, 1.day.from_now, nil].each {|d| puts d.try(:to_s, :admin)}