How to Manage Environment Variables in Rails

June 2, 2022   • rails

Now you might think it’s so easy to access them using the ENV hash. Why do we need a different way?

Well, a very common problem when working on multiple Rails applications on the same machine during development is that these applications might have environment variables with the same name. A good example is the database connection string. Different applications will have a different value for the same environment variable. If you set the environment variable in your shell config file, how can you use different values?

The same problem will happen in a Continuous Integration (CI) server, where you might have multiple projects running.

So, don’t set the environment variables on the development machines or CI servers. Use the dotenv gem that lets you load variables from a .env file into the ENV hash when the Rails application loads.

Let’s see how to use this gem.

Add this line to the top of your application’s Gemfile:

# A Ruby gem to load environment variables from `.env`.
gem 'dotenv-rails', groups: [:development, :test]

Then install the gem using Bundler:

$ bundle

Add your application configuration to your *.env* file at the root of your project:

S3_BUCKET=YOURS3BUCKET
SECRET_KEY=YOURSECRETKEYGOESHERE

Whenever your application loads, these variables will be available in ENV:

config.fog_directory  = ENV['S3_BUCKET']

Don’t forget to add the .env file to the .gitignore file, so you don’t accidentally push it to Github for the whole world to see.

Note: As a hack, you could simply prefix the environment variable with the application name, e.g. BLOG_S3_BUCKET, and it will work, but still, it would be nice to have the environment variables nicely scoped within the application and with a concise name.