如何在 yaml 列出关联数组名单

我试图在 yaml 中存储一些配置变量,这些变量被表示为一个关联数组字典。 我是这么做的:

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

当我试图从 ROR init 文件中解析它时,这会产生一个异常:

Nil 的未定义方法‘ symize _ keys!’: NilClass

下面是我如何启动它:

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

我猜我的 yaml 语法是错误的,那么如何正确地写呢?

58789 次浏览

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.

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

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

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