This project is archived and is in readonly mode.
ignore_nil{} as a better alternative to try()
Reported by Steven Soroka | March 27th, 2009 @ 09:05 PM | in 2.x
ignore_nil is actually short for "ignore no method error on nil", referring to the error you get if you call a method on an object that is unexpectedly nil. This can happen if you chain method calls together and one of the methods returns a nil.
ignore_nil{} will return nil if you get a NoMethodError exception on NilClass. any other exception type is reraised so that code inside ignore_nil{} blocks don't become a black- hole.
==== Examples
Without ignore_nil:
@user && @user.address && @user.address.street
or worse:
@user.address.street rescue nil
(worse because it catches everything! even if address doesn't have a street method!)
With ignore_nil:
ignore_nil { @user.address.street }
Comments and changes to this ticket
-
Steven Soroka March 27th, 2009 @ 09:07 PM
- no changes were found...
-
Joel Chippindale July 21st, 2009 @ 05:25 AM
Your example could be written as follows with try
@user.try(:address).try(:street)
What makes using ignore_nil an improvement?
-
Steven Soroka July 21st, 2009 @ 03:10 PM
I don't think .try().try().try().try() is attractive, and it's definitely not DRY.
Much easier to edit and maintain a block around the code than .try sprinkled throughout method calls in the code.
No reason we couldn't support both, I'd think.
-
Pratik July 21st, 2009 @ 04:01 PM
- State changed from new to wontfix
I don't think you should chain try(). So I'm happy with that looking ugly. Don't think something like ignore_nil belongs in core.
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>