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 a
Just use appropriate option in your YAML parser. For instance, symbolize_names
in Psych:
APP_CONFIG = YAML.load(File.read(File.expand_path('../app.yml', __FILE__)), symbolize_names: true)
See RDoc: https://ruby-doc.org/stdlib-2.6.1/libdoc/psych/rdoc/Psych.html#method-c-load.
If you're using pure Ruby (i.e. no Rails), you could intermediately change to JSON format. The JSON lib's parse
method can symbolize keys.
http://ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html#method-i-parse
Here's what I mean:
JSON.parse(JSON.dump(YAML.load_file(File.expand_path('../app.yml', __FILE__))), symbolize_names: true)
Note: This adds overhead of conversion to and from json.
Psych (a.k.a. YAML) provides the keyword argument :symbolize_names
to load keys as symbols. See method reference
file_path = File.expand_path('../app.yml', __FILE__)
yaml_contents = File.read(file_path)
APP_CONFIG = YAML.safe_load(yaml_contents, symbolize_names: true)
This is the same from the selected answer, but with a better syntax:
YAML.load(File.read(file_path)).with_indifferent_access
I usually don't use HashWithIndifferentAccess
just to avoid confusion and prevent inconsistencies in the way that it is accessed, so what I would do instead is tack on a .deep_symbolize_keys
to get the whole thing in symbol key form.