Skip to content

Instantly share code, notes, and snippets.

@sukima
Created August 5, 2010 21:48
Show Gist options
  • Save sukima/510438 to your computer and use it in GitHub Desktop.
Save sukima/510438 to your computer and use it in GitHub Desktop.
How to customize a global config YAML load in rails

I found this great RailsCast about making a global configuration. And further offered through the Nifty Generators (script/generate nifty_config) However I wanted to further customize it by allowing global configurations regardless of the environment.

For example this is the original idea: # config/config.yml development: perform_authentication: false

test:
  perform_authentication: false

production:
  perform_authentication: true
  username: admin
  password: secret

This would require that there be a lot of repetition. What I wanted was a way to write a global variable once and still keep differences for the environments. I eventually thought of this solution to manipulate the hash after the fact (avoiding the warnings that a constant variable being changed).

The sample file config.yml shows the new format while load_config.rb is the code to make it all happen.

This will produce the following config when RAILS_ENV is development: APP_CONFIG[:global_var1] #=> "foo" APP_CONFIG[:global_var2] #=> "bar" APP_CONFIG[:env_var] #=> "foobar"

In a rails application you can put load_config.rb into config/initializers directory.

global_var1: "foo"
global_var2: "bar"
environments:
development:
env_var: "foobar"
test:
env_var: "barfoo"
# Uses local config via YAML.
# http://gist.github.com/510438
APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")
APP_CONFIG.merge!(APP_CONFIG['environment'][RAILS_ENV])
APP_CONFIG.delete('environment')
APP_CONFIG.symbolize_keys
@niyando
Copy link

niyando commented Jan 31, 2015

typo error:

APP_CONFIG.merge!(APP_CONFIG['environments'][RAILS_ENV])
APP_CONFIG.delete('environments')

bang at the end

APP_CONFIG.symbolize_keys!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment