簡體   English   中英

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

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

如何在 Rails 7 應用程序中為設置的環境變量配置“dotenv gem”。

Gemfile中添加以下行

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

運行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

在 app 文件夾中創建一個名為.env的文件 在這個.env文件中添加您的憑據,如下所示

DB_USERNAME: username
DB_PASSWORD: password

在適當的地方使用這個環境變量,如下所示。 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'] %>

現在您的 ENV 變量設置已完成。 您可以像下面這樣從 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