Swallow Nil

Dan Croak

I’ve been using this for about a year and a half.

Abomination or legitimate tool for the box?

Usage

two dots or more. nil anywhere in the chain is an acceptable response.

campaign = swallow_nil { supporter.politician.campaign }

Definition

def swallow_nil
  yield
rescue NoMethodError
  nil
end

try()

It’s similar to try from ActiveSupport except for chains instead of individual methods.

Law of Demeter

Are you strict about Law of Demeter violations?

Or, do you find yourself with occasional chains like this that could benefit from swallow_nil() or try() or andand()?