Environment-based configuration in Ruby

August 23, 2010 by alex

A while ago I created a simple class to allow management of configuration via YAML files, similar to Rails' config/database.yml. Seems like this might be useful in other contexts besides the one I created it for, so I just pulled the code into its own public GitHub repository.

http://github.com/alexdean/envbasedconfig

You create a YAML file like this, with the top-level keys matching your environment names.

development:
  server: dev-server
  port: 8080
test:
  server: test-server
  port: 8080
production:
  server: production.com
  port: 80

Then define a configuration class like

class AppConfig < EnvBasedConfig
  set_configuration "config/app.yml"
end

The default behavior is to figure out which YAML block to used based on Rails.configuration.environment , but that’s easy to change by providing your own implementation of env.

class AppConfig < EnvBasedConfig
  def env
    # your logic for selecting the correct environment here
  end
  set_configuration "config/app.yml"
end

Code which needs access to this configuration information should make calls like AppConfig.server. In the test environment, this returns test-server.

☙ ☙ ☙