Rails load YAML to hash and reference by symbol

Michael K Madison picture Michael K Madison · Aug 16, 2011 · Viewed 47.4k times · Source

I am loading a YAML file in Rails 3.0.9 like this:

APP_CONFIG = YAML.load(File.read(File.expand_path('../app.yml', __FILE__)))

It loads the all of the contents like hierarchical hashes, no problem. The part I don't like is the fact that the hashes can only be accessed with single or double quotes but not a symbol.

APP_CONFIG['mailer']['username']  # works fine
APP_CONFIG[:mailer][:username]    # doesn't

Any thoughts?

Answer

Rob Di Marco picture Rob Di Marco · Aug 16, 2011

Try using the HashWithIndifferentAccess like

APP_CONFIG = HashWithIndifferentAccess.new(YAML.load(File.read(File.expand_path('../app.yml', __FILE__))))