André Laszlo
André Laszlo

Reputation: 15537

Environment variables cached in Rails config?

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:

In a fresh app (I'm using Ruby 2.0.0 and Rails 4.2.1), edit 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:

$ 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:

$ 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?

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.

Upvotes: 15

Views: 6151

Answers (1)

Andr&#233; Laszlo
Andr&#233; Laszlo

Reputation: 15537

The Spring gem is preloading apps by default in the development environment in 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.watch '.env'

Upvotes: 26

Related Questions