You will most probably need to have at least one particular
case where you need to store configuration values for your
Rails application. Saving these types of values in the
environment is one of the principles of a
twelve-factor app. It is
thus recommended to use a separate file and use environment
variables inside your code so that you do not have to change
the same value in multiple places. This, however, is not
something that you can do really easily unless you use
something really helpful like dotenv.
Dotenv is a Ruby gem that during the bootstrap loads variables
from a .env file into the environment that you are running
your application.
It is really to use and all you have to do to install it is
place the following line in your Gemfile:
gem ‘dotenv-rails’, groups: [:development, :test]
Then, of course, you need to run bundle.
Now you need to place your configurations inside
.env file in the root of your project:
AUTH0_CLIENT_ID=YOURAUTH0CLIENTID
SECRET_KEY=YOURSECRETKEYGOESHERE
You can then access them using
ENV.fetch[‘SECRET_KEY’] or
ENV[‘SECRET_KEY’]. Note that if you use
ENV.fetch[], you can learn about unset environment
variables during the deploy.
According to its
README file,
dotenv is initialized in your Rails app during the
before_configuration callback, which is fired when
the Application constant is defined in
config/application.rb with class
Application < Rails::Application. If you need it
to be initialized sooner, you can manually call
Dotenv::Railtie.load.
You can view its source
code and learn more about it by going on
Github.