简体   繁体   English

如何在 Rails 7 应用程序中配置“dotenv gem”

[英]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.如何在 Rails 7 应用程序中为设置的环境变量配置“dotenv gem”。

Add the below line in the GemfileGemfile中添加以下行

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运行bundle installapplication.rb中的Bundler.require(*Rails.groups)行下方添加以下代码

# 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在 app 文件夹中创建一个名为.env的文件 在这个.env文件中添加您的凭据,如下所示

DB_USERNAME: username
DB_PASSWORD: password

Use this env variable in the appropriate place like below.在适当的地方使用这个环境变量,如下所示。 in the database.ymldatabase.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.现在您的 ENV 变量设置已完成。 you can check it from the rails console like below.您可以像下面这样从 Rails 控制台检查它。

rails c
> ENV["DB_USERNAME"]
> username
>ENV["DB_PASSWORD"]
> password

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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