环境变量缓存在Rails配置中?

时间:2022-06-02 22:46:11

This behavior is really confusing me. It seems like the content of my ENV or my configuration is cached somewhere. Here's how to reproduce it:

这种行为让我很困惑。似乎我的ENV或我的配置的内容被缓存到某个地方。以下是如何重现它:

In a fresh app (I'm using Ruby 2.0.0 and Rails 4.2.1), edit application.rb:

在一个新的应用程序(我使用Ruby 2.0.0和Rails 4.2.1)中,编辑application.rb:

$ cat config/application.rb 
require File.expand_path('../boot', __FILE__)

require 'rails/all'

Bundler.require(*Rails.groups)

module Myapp
  class Application < Rails::Application
    config.active_record.raise_in_transactional_callbacks = true

    config.env_foo = ENV['FOO']
  end
end

The configuration item env_foo is now nil:

配置项env_foo现在为零:

$ unset FOO  # make sure FOO is unset
$ rails console
Loading development environment (Rails 4.2.1)
2.0.0-p598 :001 > Rails.application.config.env_foo
 => nil

Set some environment variables and see what happens:

设置一些环境变量,看看会发生什么:

$ export FOO=barbapapa
$ rails console
Loading development environment (Rails 4.2.1)
2.0.0-p598 :001 > Rails.application.config.env_foo
 => nil 
2.0.0-p598 :002 > ENV['FOO']
 => "barbapapa" 

So the cache item is still nil but ENV has changed. Even if I change environment to production:

所以缓存项仍然是零,但ENV已经改变。即使我将环境改为生产:

$ RAILS_ENV=production rails console
Loading production environment (Rails 4.2.1)
2.0.0-p598 :001 > Rails.application.config.env_foo
 => nil

Where is this configuration cached and how do I make it reflect the new ENV?

缓存此配置的位置以及如何使其反映新的ENV?

Note: I know that there are other ways to configure Rails, but I'm using Heroku so I think using the environment for configuration is encouraged.

注意:我知道还有其他方法可以配置Rails,但我正在使用Heroku,所以我认为使用环境进行配置是值得鼓励的。

1 个解决方案

#1


16  

The Spring gem is preloading apps by default in the development environment in Rails 4.

Spring gem在Rails 4的开发环境中默认预加载应用程序。

To reload your app, simply kill the spring processes for the current project:

要重新加载您的应用,只需终止当前项目的弹出过程:

spring stop

Spring doesn't seem to be able to refresh on environment changes, but it does monitor files. If you are using an .env file, with dotenv for example, you can add it to config/spring.rb:

Spring似乎无法在环境变化时刷新,但它确实监视文件。如果您使用的是.env文件,例如使用dotenv,则可以将其添加到config / spring.rb:

Spring.watch '.env'

#1


16  

The Spring gem is preloading apps by default in the development environment in Rails 4.

Spring gem在Rails 4的开发环境中默认预加载应用程序。

To reload your app, simply kill the spring processes for the current project:

要重新加载您的应用,只需终止当前项目的弹出过程:

spring stop

Spring doesn't seem to be able to refresh on environment changes, but it does monitor files. If you are using an .env file, with dotenv for example, you can add it to config/spring.rb:

Spring似乎无法在环境变化时刷新,但它确实监视文件。如果您使用的是.env文件,例如使用dotenv,则可以将其添加到config / spring.rb:

Spring.watch '.env'