The Proper Way To Fetch Environment Variables In Ruby

The 3rd factor of a 12 factor app is configuration stored in the environment. Now that it's in your environment, how do you access them?

Normally, in ruby, you access the values of the ENV hash like this:

ENV["SUPER_IMPORTANT_PASSWORD"]
=> “asdfuekclaR#$”

But, sometimes you can forget to set the value – what happens then?

ENV["SUPER_IMPORTANT_PASSWORD"]
=> nil

That’s no good! We should know if our environment variables aren’t present when they’re called!

Enter .fetch.

.fetch is a seldom used method on Hash objects that will raise an exception if the key doesn’t exist, or if a default value is passed in, it uses that.

irb(main):005:0> ENV.fetch("SUPER_IMPORTANT_PASSWORD", "really_insecure_password")
=> "really_insecure_password"
irb(main):004:0> ENV.fetch("SUPER_IMPORTANT_PASSWORD")
KeyError: key not found: "SUPER_IMPORTANT_PASSWORD"
        from (irb):4:in `fetch'
        from (irb):4
        from /Users/jrg/.rbenv/versions/2.3.3/bin/irb:11:in `<main>'

I lean towards using .fetch without a default for two reasons – one, I rarely have a default that will work in most situations. two, I prefer to be explicit with my application requirements, and I believe that configuration (even if it’s via the environment) is an application requirement.

For further reading on cool stuff in ruby’s hash, take a look at the documentation for it . Hash is one of the most used data types in ruby, but most people barely scratch the surface with it (myself included).

Leave a Reply

Your email address will not be published. Required fields are marked *