DEV Community

matt swanson
matt swanson

Posted on • Originally published at boringrails.com on

Ensure required environment variables are set when booting up Rails

It’s common to use environment variables to configure external services or other options in a Rails app. These ENV_VARS usually are not checked into source control, but rather configured per environment.

Rails has the concept of initializers, which is code run during the boot phase of a Rails app.

You can add a custom initializer to check that required environment variables are set to avoid exceptions later on when your code expects a value to exist.

Usage

Create a new initializer in your app and add the required variables:

# config/initializers/01_ensure_environment.rb

if Rails.env.development?
  %w[
    AWS_ACCESS_KEY_ID
    AWS_SECRET_ACCESS_KEY
    S3_BUCKET
    ALGOLIA_ID
    ALGOLIA_API_KEY
    ALGOLIA_SEARCH_KEY
    ALGOLIA_INDEX
    ALGOLIA_CAMPAIGN_INDEX
    TWITTER_API_SECRET
    TWITTER_API_TOKEN
  ].each do |env_var|
    if !ENV.has_key?(env_var) || ENV[env_var].blank?
      raise <<~EOL
      Missing environment variable: #{env_var}

      Ask a teammate for the appropriate value.
      EOL
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Options

Rails initializers are loaded and executed in alphabetical order. So use a name like 01_ensure_environment.rb to control the sort order and make sure this one loads first.

You may wish to check in a sample .env.sample file into git (without any values) to make it easier for new team members to get their environment into a working state.

Additional Resources

Rails Doc: Configuring Rails apps


Discussion (0)