How to configure the “dotenv gem” in the rails 7 application for the set environment variable.
32 Answers
Most of what Pooja is saying is effectively incorrect. The .env file goes into the root of your application, not in the app folder. The syntax of the env vars in .env are delimited with "=" not ": ". For example, a .env would look like this, which similar to how it is done in Node apps:
MYSQL_USERNAME=user
MYSQL_PASSWORD=password
MYSQL_HOST=hostIn her snippet above, she only includes the development block in Gemfile, yet performs a check on both development and test in application.rb when loading dotenv. In that case, the Gemfile should look like this and preferably add the gem to the top:
gem 'dotenv-rails', groups: [:development, :test]In fact, everything I am saying is fundamentally taken from the Gem home page:
Add the below line in the Gemfile
gem 'dotenv-rails', require: 'dotenv/rails-now', groups: [:development]Run bundle installAdd the below code just below this line Bundler.require(*Rails.groups) in the application.rb
# Load dotenv only in development or test environment
if ['development', 'test'].include? ENV['RAILS_ENV']
Dotenv::Railtie.load
endCreate one file in the app folder with .env name
Add your credentials in this .env file like below
DB_USERNAME: username
DB_PASSWORD: passwordUse this env variable in the appropriate place like below.
in the database.yml
default: &default adapter: postgresql encoding: unicode pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> host: localhost username: <%= ENV['DB_USERNAME'] %> password: <%= ENV['DB_PASSWORD'] %>Now your ENV variable setup is done. you can check it from the rails console like below.
rails c
> ENV["DB_USERNAME"]
> username
>ENV["DB_PASSWORD"]
> password 1