I have a huge config yaml file, where all of the nodes should be read as strings. An example:
model_names:
Audi:
A4:
- A4
- A 4
Fiat:
500:
- 500
I load out the file in rails:
catalogue = File.read("#{Rails.root}/config/cars_catalogue.yml")
CARS_CATALOGUE = YAML.load(catalogue)
My problem is, that if I ask for:
CARS_CATALOGUE['model_names']['Fiat']['500']
It returns nil, because it thinks that 500: is a fixnum - but all of the nodes should ALWAYS be strings - and i don't want to enforce this with quotes everywhere in the yaml file. So how do I do this in a simple and smart way?
Can you regenerate the file? If yes, then simply add quotes to the numbers:
model_names:
Audi:
A4:
- A4
- A 4
Fiat:
"500":
- 500
That should do it.
stringify_keys
should convert all keys to string
catalogue = File.read("#{Rails.root}/config/cars_catalogue.yml")
CARS_CATALOGUE = YAML.load(catalogue).stringify_keys
Still better to use YAML.load(catalogue).symbolize_keys
to convert all keys to symbols
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With