在引导文件中加载环境变量

Load environment variable in boot file

我在 boot.rb 中加载环境变量时遇到问题。我尝试使用 2 个 gems dotenv & dotenv-rails 但其中 none 对我有用。其他地方我可以使用环境变量但不能在 boot.rb 中使用。有人对此有任何线索

if ["development"].include?(ENV['RAILS_ENV'])
   require 'bootsnap/setup'
   
   Bootsnap.setup(
    cache_dir:            'tmp/cache',          # Path to your cache
    development_mode:     'development', # Current working environment, e.g. RACK_ENV, RAILS_ENV, etc
    load_path_cache:      true,                 # Optimize the LOAD_PATH with a cache
    autoload_paths_cache: true,                 # Optimize ActiveSupport autoloads with cache
    compile_cache_iseq:   true,                 # Compile Ruby code into ISeq cache, breaks coverage reporting.
    compile_cache_yaml:   true                  # Compile YAML into a cache
  )
end

您可以根据需要使用 loadrequire 来明确处理您的 .env 文件,然后再测试环境变量。

DotEnv 只会在 Gem 加载后将您的 .env 文件加载到环境中。

在 Rails 中,这是由 config/application.rb 中的行 Bundler.require(*Rails.groups) 完成的。如果您需要在此之前访问环境变量,则需要手动调用 Dotenv::Railtie.load:

Bundler.require(*Rails.groups)
Dotenv::Railtie.load

或者至少是 what the readme would lead you to belive。除了 Railtie,我想你可以使用普通的 ruby 方法:

require 'dotenv'
Dotenv.load 

但是有很多选项可以从 direnv 之类的文件中设置 ENV 变量,它不是 Ruby gem 并且挂钩到您的 shell 本身。