How to make all nodes in yaml be strings

I have a huge yaml configuration file where all nodes should be read as strings. Example:

model_names: Audi: A4: - A4 - A 4 Fiat: 500: - 500 

I upload the file to the rails:

 catalogue = File.read("#{Rails.root}/config/cars_catalogue.yml") CARS_CATALOGUE = YAML.load(catalogue) 

My problem is that if I ask:

 CARS_CATALOGUE['model_names']['Fiat']['500'] 

It returns nil because it thinks 500: this is fixnum, but all nodes should ALWAYS be strings - and I don't want to use this with quotes everywhere in the yaml file. So how do I do this in a simple and smart way?

+4
source share
3 answers

stringify_keys should convert all keys to string

 catalogue = File.read("#{Rails.root}/config/cars_catalogue.yml") CARS_CATALOGUE = YAML.load(catalogue).stringify_keys 

Even better, use YAML.load(catalogue).symbolize_keys to convert all keys to characters

+2
source

Can you recover the file? If so, just add quotation marks to the numbers:

 model_names: Audi: A4: - A4 - A 4 Fiat: "500": - 500 

That should do it.

+5
source

Rails currently has a function to recursively type stringificaiton; check him

+1
source

Source: https://habr.com/ru/post/1369488/


All Articles