2015-02-17
Say you’re in Rails and want check that a method exists & that it is not nil:
.my_method my_object
One way you could do this is:
if my_object
if my_object.my_method
.my_method
my_objectend
end
If you were cleverer, you could just do:
if my_object && my_object.my_method
.my_method
my_object...
The trouble with these approaches is they can become cumbersome:
if my_object &&
.my_method &&
my_object.my_method.my_second_method
my_object
.my_method.my_second_method my_object
And that’s using the more concise syntax… A better approach would be to use the Object#try method. It ‘tries’ an object’s method and, instead of going mental, calmly returns nil if that method doesn’t work.
.try(:my_method) my_object
Ta da! This makes the more nested existence-validations read much better:
.try(:my_method).try(:my_second_method) my_object
If you’re using standard ruby, the #defined?
and
#nil?
methods could help…