The environment variables values tend to differ for each system:
set # ... HOME=/home/christian HOST=antigua IRBRC=/home/christian/.rvm/rubies/ruby-2.3.0/.irbrc # ...
Accessing the environment variables in Ruby
In Ruby environment variables can be readout quite easily:
ENV['RUBY_VERSION'] # => "ruby-2.3.0"
However, it is often necessary to set environment variables for different reasons. Especially in the development and test environment, the variables should be fast, simple and always available. In addition, the variables often have to differ according to the environment.
Gem dotenv for envoronment variables
There are several Ruby Gems that allow configuration of the environment variables (also depending on the environment).
The Gem rails-dotenv is probably the most widespread.
It is based on .env files. First, it expects a .env file with key-value pairs:
# .env AWS_SECRET_ACCESS_KEY=A-very-fancy-secret-key-123 DATABASE_URL="postgres://christian@localhost/my_database"
ENV['AWS_SECRET_ACCESS_KEY'] # => "A-very-fancy-secret-key-123"
Different environments (development, test, production) tend to require different variables. For this purpose, environment specific .env files should be created. The file names follow the pattern .env__.environment__, so to speak .env.development or .env.test. All valid variables remain in the .env.
# .env AWS_SECRET_ACCESS_KEY=A-very-fancy-secret-key-123
# .env.test DATABASE_URL="postgres://christian@localhost/test_db"
# .env.development DATABASE_URL="postgres://christian@localhost/development_db"
Flexible environment variables
The values can also be generated in flexible way. For example, it would be awkward if each developer had to create a new user for their development database.
DotEnv can handle Bash commands:
# .env.development DATABASE_URL="postgres://$(whoami)@localhost/development_db"
ENV['DATABASE_URL'] # => "postgres://christian@localhost/my_database"
If other Gems depend on certain environment variables, dotenv-rails should be loaded before these Gems in the Gemfile.
It is important to note that sensitive information should never be checked into version control. Therefore, DotEnv should be used to set up development systems quickly and reliably. In the production system there should be used different values for security reasons. Another reason is to prevent compromising external systems by development machines.