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

hound

Hound automatically reviews Ruby, JavaScript, CoffeeScript, and SCSS code in your GitHub pull requests and comments on style violations. It is free for open source repos and $12/month per private repo.