Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

ignore_nil{} as a better alternative to try()

#2364

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 }

Reported by Steven Soroka · March 27th, 2009 @ 09:05 PM

State: wontfix
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. Steven Soroka
  2. Joel Chippindale
    Joel Chippindale

    Your example could be written as follows with try

    @user.try(:address).try(:street)
    

    What makes using ignore_nil an improvement?

    July 21st, 2009 @ 05:25 AM

  3. Steven Soroka
    Steven Soroka

    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.

    July 21st, 2009 @ 03:10 PM

  4. Pratik
    Pratik
    • 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.

    July 21st, 2009 @ 04:01 PM