How to make a list of associative array in yaml

Ruby on-RailsDictionaryYamlAssociative Array

Ruby on-Rails Problem Overview


I'm trying to store some configuration variables in yaml represented as an associative array aka dictionary. Here is how I did:

content_prices:                                                                                                                                                                                                                               
  - {country: AU, price: 6990000}                                                                                                                                                                                                             
  - {country: AT, price: 4990000}                                                                                                                                                                                                             
  - {country: BE, price: 4990000}  

This produce an exception when I try to parse it from my ROR init files:

> undefined method `symbolize_keys!' for nil:NilClass

Here is how I init it:

Config = YAML.load_file("#{Rails.root}/config/prices.yml")[Rails.env].symbolize_keys!

I guess my yaml syntax is wrong, then how to write it properly ?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Your YAML looks okay, or you can configure an array of hashes like this :

content_prices:
  - country: AU
    price: 6990000
  - country: AT
    price: 4990000
  - country: BE
    price: 4990000

Which will load as the following hash:

{"content_prices"=>[
  {"country"=>"AU", "price"=>6990000}, 
  {"country"=>"AT", "price"=>4990000}, 
  {"country"=>"BE", "price"=>4990000}]}

But that still doesn't give you any reference to the Rails.env in the main hash. The problem seems to be what you're expecting to be in your hash rather than the format of the YAML.

Solution 2 - Ruby on-Rails

Not on rails, but on Symfony2 php, I had to configure the yml file like this:

content_prices:

  • country: AU price: 6990000
  • country: AT price: 4990000
  • country: BE price: 4990000

Solution 3 - Ruby on-Rails

Just in case someone wants to use dynamic keys, it is also possible:

AppBundle\Service\MailerService:
    lazy: false
    arguments:
      $defaultFrom:
        '%mailer_user%': '%mailer_name%'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAntziView Question on Stackoverflow
Solution 1 - Ruby on-RailsShadwellView Answer on Stackoverflow
Solution 2 - Ruby on-RailssinhixView Answer on Stackoverflow
Solution 3 - Ruby on-RailsGrumpyHatView Answer on Stackoverflow