Ruby’s Lonely Operator or Safe Navigation Operator

Poking through some Pull Requests I spotted syntax I’ve never seen before and found difficult to google:

person&.job&.company&.id

The “&.” was introduced in Ruby 2.3.0 as the Lonely Operator. It prevents the error “NoMethod error on Nil”. If the object is nil it just returns nil. Otherwise it continues down the chain and gives the intended result.

This allows us to skip the heavy handed code of

person && person.job && person.job.company && person.job.company.id

Using the Lonely Operator looks better. It does have valid criticisms against it. First, it doesn’t address the original issue: having a null object when you weren’t expecting it. A reliable and recommended solution is the Null Object Pattern.  An author by the name Franzejr has a clear Ruby implementation of the Null Object Pattern.

Second, this encourages us to violate the Law of Demeter.  The problem of getting a persons company id is the tight coupling between those objects. This increases the cost of maintenance and chances for technical debt.

I’m curios to see where the Lonely Operator goes. I’m happy to have it in my tool belt. It simplifies chaining multiple methods. It accommodates legacy code where the Null Object Pattern may complicate a code base further.

While researching Ruby’s Lonely Operator I found the following articles helpful:

Let me know what you think in the comments. I’m curios how often you find the Lonely Operator in the wild and if you use it.

The Dot Forward File

When starting Terminal you may notice a ‘You have mail’ message. You may even know of the mail command and how to traverse your mail.

This can be unexpected if you’ve never configured a script or service to send mail to your user. However, some services, like crontab, are configured to send STDOUT to your mail account by default.

The convenience of mailing logs, error reports, or statuses can be sullied by learning and tracking another system. As always, there is an easier way.

A .forward file or ‘dot forward file’ in your home directory will  tell your system where that mail should go. Simply running the below will redirect that mail to your account.

echo "me@mail.com > ~/.forward"

You can include multiple addresses and separate them by comma “me@mail.com, you@mail.com”.

This allows you to receive the notifications in the mail application of your choice.

The dot forward file is a part of dot-courier. It can be configured to send mail to a program or append to a file. I found Dr. Nikolai Bezroukov’s article to be helpful in understanding what the dot forward file can do.