15

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.

1 Answer 1

26

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'
4
  • answering your own question at the same minute as the question? :D Feb 13, 2018 at 3:49
  • 2
    @lutfianasari Yes :) I know it looks funny but it's actually encouraged. stackoverflow.com/help/self-answer Feb 13, 2018 at 8:54
  • 1
    ah, I see.. I saw others also answer their own question, but you said "you" in the above answer and that made me questioning :D sorry for my useless comment and thanks for the information link :) Feb 14, 2018 at 5:20
  • :-) Sometimes I only read answers so I wanted to be consistent. I tried sticking to the generic you to be less confusing. en.wikipedia.org/wiki/Generic_you Feb 14, 2018 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.