rails < 4.0 "try" method throwing NoMethodError?
This is what try does
Invokes the method identified by the symbol method, passing it any arguments and/or the block specified, just like the regular Ruby Object#send does. Unlike that method however, a NoMethodError exception will not be raised and nil will be returned instead, if the receiving object is a nil object or NilClass.
So, let's say you setup @user
in your controller but you didn't instantiate it then @user.try(:foo)
=> nil
instead of
@user.foo
NoMethodError: undefined method `foo' for nil:NilClass
The important point here is that try is an instance method. It also doesn't return nil if the object you try on isn't nil.
Rails 3
You misunderstand how try
works, from the fine manual:
try(*a, &b)
Invokes the method identified by the symbol method, passing it any arguments and/or the block specified, just like the regular RubyObject#send
does.Unlike that method however, a
NoMethodError
exception will not be raised andnil
will be returned instead, if the receiving object is anil
object orNilClass
.
And the version of try
that is patched into NilClass
:
try(*args)
Callingtry
onnil
always returnsnil
.
So try
doesn't ignore your attempt to call a non-existent method on an object, it ignores your attempt to call a method on nil
and returns nil
instead of raising an exception. The try
method is just an easy way to avoid having to check for nil
at every step in a chain of method calls.
Rails 4
The behavior of try
has changed in Rails 4 so now it:
Invokes the public method whose name goes as first argument just like
public_send
does, except that if the receiver does not respond to it the call returnsnil
rather than raising an exception.
So now try
takes care of both checks at once. If you want the Rails 3 behavior, there is try!
:
Same as
try
, but will raise aNoMethodError
exception if the receiving [sic] is notnil
and does not implemented [sic] the tried method.