Last Updated: February 25, 2016
·
4.735K
· sorens

Easy Environment or Config Override in Rails

Do you use a lot of environment variables in your Rails application? Tired of having to set and then change ENV variables in your development environment? Want to do it in Rails instead?

config/application.rb

Module MyApp
  class Application < Rails::Application
    # assign the ENV variable to a config value
    config.test                 = ENV['TEST']
  end
end

lib/config/environment_override.rb

class EnvironmentOverride
  def self.load
    override = File.join( Rails.root, "config", "overrides", "#{Rails.env}.rb" )
    if File.exists? override
      puts "loading override configuration for #{Rails.env}"
      require override
    end
  end
end

at the end of config/environments/development.rb

MyApp::Application.configure do
  # load the override environment
  EnvironmentOverride.load
end

create config/overrides/development.rb

MyApp::Application.configure do
  # now, you can override your ENV variables
  config.test    ||= true # or whatever you need
end

restart your server. When you need to change an ENV value, edit your config/overrides/development.rb file and restart your server.

Additionally, I put the config/overrides directory in my .gitignore file so that I don't push my custom settings to my co-workers. This makes a nice place to customize settings for your development setup without the possibility of it reaching other developers. To help new developers, I include a template override file to help give example of how to expand it.

Note: you can do the same thing with the test environment if you so desire.

I know some developers don't find changing their local ENV values to be that burdensome, but I prefer to have as much of the state as possible in the Rails system.

YMMV