【问题标题】:Load environment variable in boot file在引导文件中加载环境变量
【发布时间】:2023-03-22 18:23:01
【问题描述】:

我在 boot.rb 中加载环境变量时遇到问题。我尝试了 2 颗宝石 dotenv 和 dotenv-rails,但没有一个对我有用。其他地方我可以使用环境变量,但不能在 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

【问题讨论】:

  • 你没有说RAILS_ENV的内容是什么,但是由于你的数组只有一个元素("development"),你可以将你的条件重写为if ENV['RAILS_ENV'] == "development"。它与您当前的代码相同,但更易于理解。
  • RAILS_ENV=development 在 .env 文件中设置
  • 也许可以,但值是多少?另外,您确定.env 文件在执行此代码时已被处理吗?我建议打印出这个值进行调试。
  • 我尝试调试它给出的 ENV['RAILS_ENV'] 的值为零。但是当我在 Rails 控制台或应用程序的任何地方检查时,它给了我正确的值。我怀疑是在启动时 .env 文件未加载
  • 我已经投票结束这个问题。

标签: ruby-on-rails ruby ruby-on-rails-5.2


【解决方案1】:

DotEnv 只会在 Gem 加载后将您的 .env 文件加载到 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。我猜你可以使用普通的 ruby​​ 方法来代替 Railtie:

require 'dotenv'
Dotenv.load 

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

【讨论】:

  • 谢谢它没有那样工作,但它给了我提示。当我在 application.rb 中添加 Dotenv::Railtie.load 时,它是为 Dotenv::Railtie:Class 调用的私有方法“load”。然后我在 boot.rb 中再次尝试了同一行,但它仍然不起作用。后来我在 boot.rb 中用这两行尝试过,它需要 'dotenv' Dotenv.load
  • 我猜the docs 已经坏了。我已经好几年没用过 dotenv 了。 direnv 完成了这项工作,并避免将您的 gemfile 与实际的机器特定工具混淆。
【解决方案2】:

在测试环境变量之前,您可以根据需要使用loadrequire 来显式处理您的.env 文件。

【讨论】:

    猜你喜欢
    • 2016-10-19
    • 1970-01-01
    • 2017-07-09
    • 2018-11-03
    • 1970-01-01
    • 2019-04-19
    • 2016-07-08
    • 2017-01-03
    • 2014-02-01
    相关资源
    最近更新 更多