Fix missing environment variables for production

It’s common to forget setting a new environment variable after deployment, so I’ll share a strategy that I’m using:

1. Use fetch method

Let’s start with this example of missing NEW_KEY value:

ENV["NEW_KEY"] # nil

ENV.fetch("NEW_KEY") # KeyError: key not found: "NEW_KEY"

So how this works? ENV is a hash-like accessor for environment variables so we can use hash methods but we need only fetch for the moment.

Now it’s time to add more description to the error:

ENV.fetch("NEW_KEY"){ raise "Missing NEW_KEY" } # RuntimeError: Missing NEW_KEY

We have a descriptive warning, but it’s not enough we want to know if there is a missing variable after the deployment.

2. Rails custom configuration

When we start a Rails application, “config/application.rb” is required before booting the server if you are curious to know about Rails initialization process check the official guide.

With this information, we can use Rails custom configuration (check this guide for more information) to have the following configuration:


module DemoApp
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.1

    config.x.new_key = ENV.fetch("NEW_KEY") { raise "Missing NEW_KEY" }

If we try to start a Rails server without setting the ENV variable we will get our custom Error.

Next, we need just to access the defined variable in the source code as follows:

value = Rails.configuration.x.new_key

That’s it, with this approach no more worries about missing ENV variables! 🙂