97

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 ?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Antzi
  • 12,831
  • 7
  • 48
  • 74

3 Answers3

181

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.

Shadwell
  • 34,314
  • 14
  • 94
  • 99
  • I guess, this is inline approach `key: - string1` , `key: ['string1', 'string2',` and this is contemporary object notation for associative where the above syntax is not accepted , ```- { param1: 'myvalue', param2: 'myvalue2' }``` https://stackoverflow.com/a/33136212/3419535 , https://stackoverflow.com/a/49814618/3419535 – FantomX1 Jun 03 '20 at 18:33
15

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
sinhix
  • 878
  • 6
  • 11
0

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

AppBundle\Service\MailerService:
    lazy: false
    arguments:
      $defaultFrom:
        '%mailer_user%': '%mailer_name%'
GrumpyHat
  • 281
  • 2
  • 15