【问题标题】:Using ENV files in production on Heroku在 Heroku 的生产环境中使用 ENV 文件
【发布时间】:2014-03-06 22:37:12
【问题描述】:

按照this article 中的说明,我的production.rb 环境文件中有以下配置行:

  config.cache_store = :mem_cache_store, ENV["MEMCACHEDCLOUD_SERVERS"].split(','), { :username => ENV["MEMCACHEDCLOUD_USERNAME"], :password => ENV["MEMCACHEDCLOUD_PASSWORD"] }

但是当我尝试部署时,我会得到一个错误:

运行:rake assets:precompile rake aborted!
未定义的方法split' for nil:NilClass
/tmp/build_abdc.../config/environments/production.rb:107:in
block in '

这是因为配置变量在编译期间不可用。有一个 Heroku 实验室 add-on 可以用来解决这个问题,但它带有来自 Heroku 的警告,“使用此实验室功能被认为与 Heroku 最佳实践背道而驰。”

那么,在生产配置中使用 ENV 变量时,最佳实践是什么?是否应该将它们都包裹在救援处理程序中,以便 Heroku 在编译期间忽略它们?

【问题讨论】:

  • 也许您可以尝试将设置移动到初始化程序:stackoverflow.com/questions/5810289/…
  • @steakchaser - 谢谢,但这并没有改变任何东西 - 该行仍然在编译中被击中并引发同样的错误
  • 穆哈!我喜欢资产管道!您是否尝试设置initialize_on_precompile?我不知道这在 rails4 中是否仍然存在,但它在 heroku stackoverflow.com/questions/11889131/… 上救了我好几次
  • 您确定 MEMCACHEDCLOUD_SERVERS 存在于您的环境中吗?
  • @phoet - 有趣的文章 - 所以它说“在 slug 编译期间,您的应用程序的配置变量不存在于环境中,因此您应该采取措施处理配置变量的 nil 情况”。然后它说initialize_on_precompile:“在 Rails 4.x 中,此选项已被删除,不再需要”。嗯?

标签: ruby-on-rails heroku


【解决方案1】:

我们最终只是在分配之前检查了 ENV 变量。看起来这就是您在 Heroku 上的 config/initializers 中使用 ENV vars 时需要的模式:

  # NOTE: ENV vars aren't available during slug compilation, so we must check if they exist:
  if ENV["MEMCACHEDCLOUD_SERVERS"]
    config.cache_store = :mem_cache_store, ENV["MEMCACHEDCLOUD_SERVERS"].split(','), { :username => ENV["MEMCACHEDCLOUD_USERNAME"], :password => ENV["MEMCACHEDCLOUD_PASSWORD"] }
  end

另请参阅: https://devcenter.heroku.com/articles/rails-asset-pipeline#failures-in-the-assets-precompile-task

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-25
    • 2021-05-16
    • 1970-01-01
    • 2018-08-26
    • 2021-03-14
    • 2012-10-26
    • 2023-02-13
    • 1970-01-01
    相关资源
    最近更新 更多