Today I Learned

hashrocket A Hashrocket project

Fetch your Environmental Variables

It's important to fetch Ruby environmental variables rather than directly referencing them.

This code depends on 'secret_key':

key = ENV['secret_key']

When 'secret_key' is not set, 'key' will be assigned nil, which is an object.

Later, a call to key.upcase will produce a NoMethodError, because Ruby doesn't know how to uppercase nil.

This is better:

key = ENV.fetch('secret_key')

Now, when 'secret_key' is not set, KeyError will be raised. The code fails fast.

fetch takes a second argument as a default, which means you can even prevent KeyError from ever happening, if you choose:

key = ENV.fetch('secret_key', 'some_default_numbers')

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.