Skip to content

Instantly share code, notes, and snippets.

@stevenyap
Created November 12, 2014 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevenyap/2c88dd7fe852d02f1655 to your computer and use it in GitHub Desktop.
Save stevenyap/2c88dd7fe852d02f1655 to your computer and use it in GitHub Desktop.
Using Dotenv for multiple environments

Storing configuration in the environment is one of the tenets of a twelve-factor app and Dotenv is a good gem to extract your environment variables from your app to a .env file which is added to .gitignore so that it is kept private. Dotenv Github: https://github.com/bkeepers/dotenv

However, dotenv only works in development AND test environment and is not able to differentiate the environment in order to load different environment variables. eg. Your development uses a different API url than your test case.

Luckily the author has also published another gem that makes dotenv environment-aware at https://github.com/bkeepers/dotenv-deployment

Install the gem

#Gemfile
group :development, :test do
  gem 'dotenv-deployment'
end

# and run bundle... duh!

Setup your environment variables files

# .env.test at root directory
export SECRET_KEY_BASE=AAAAAAAAAAAAAAAAAAAAAA
export API_BASE_URL=http://test.com/
# .env.development
export SECRET_KEY_BASE=XXXXXXXXXXXXXXXXXXXXXX
export API_BASE_URL=http://practice.test.com/

Use Rails 4.1 secret to load the environment variables

This step is optional but it is good so that a new coder is able to deduce all the environment variables needed for the system to work instead of bumping around test cases to find out.

And using this method, the secrets.yml should be pushed to your git repository so that other coders know what is the environment variables dependencry without giving your sensitive information away.

# config/secrets.yml
development:
  secret_key_base:  <%= ENV['SECRET_KEY_BASE'] %>
  api_base_url:     <%= ENV['API_BASE_URL'] %>

test:
  secret_key_base:  <%= ENV['SECRET_KEY_BASE'] %>
  api_base_url:     <%= ENV['API_BASE_URL'] %>

production:
  secret_key_base:  <%= ENV['SECRET_KEY_BASE'] %>
  api_base_url:     <%= ENV['API_BASE_URL'] %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment