rails load environment variables

  1. Create a new Rails application or navigate to an existing one.

  2. Open the Gemfile in a text editor.

  3. Add the dotenv-rails gem to the Gemfile.

gem 'dotenv-rails', groups: [:development, :test]
  1. Save the Gemfile and run the bundle install command.
bundle install
  1. Create a new file named .env in the root directory of your Rails application.

  2. Add your environment variables to the .env file.

DB_HOST=localhost
DB_USERNAME=myuser
DB_PASSWORD=mypassword
  1. Ensure that the .env file is added to your version control system's ignore list (e.g., add it to the .gitignore file).

  2. Open the config/application.rb file.

  3. Add the following line at the top of the file to load the environment variables.

require 'dotenv/load'
  1. Save the config/application.rb file.

  2. Restart your Rails server or console for the changes to take effect.

rails server

Now, your Rails application should be able to access the environment variables defined in the .env file.