简体   繁体   中英

How to configure the “dotenv gem” in the rails 7 application

How to configure the “dotenv gem” in the rails 7 application for the set environment variable.

Add the below line in the Gemfile

gem 'dotenv-rails', require: 'dotenv/rails-now', groups: [:development]

Run bundle install Add 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
end

Create one file in the app folder with .env name Add your credentials in this .env file like below

DB_USERNAME: username
DB_PASSWORD: password

Use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM