rails load environment variables
Create a new Rails application or navigate to an existing one.
Open the Gemfile in a text editor.
Add the
dotenv-rails
gem to the Gemfile.
gem 'dotenv-rails', groups: [:development, :test]
- Save the Gemfile and run the
bundle install
command.
bundle install
Create a new file named
.env
in the root directory of your Rails application.Add your environment variables to the
.env
file.
DB_HOST=localhost
DB_USERNAME=myuser
DB_PASSWORD=mypassword
Ensure that the
.env
file is added to your version control system's ignore list (e.g., add it to the.gitignore
file).Open the
config/application.rb
file.Add the following line at the top of the file to load the environment variables.
require 'dotenv/load'
Save the
config/application.rb
file.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.