Swallow Nil

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()?

Pair with one of our expert developers to level up your skills with Coaching by thoughtbot. Save time learning best practices and techniques for reducing technical debt in Ember, Ruby, Haskell, and Go in 1-on-1 sessions tailored to your goals.