前面的冒号:YAML语法

我目前正在项目中使用Sidekiq,我有以下YAML配置文件:

:concurrency: 5 :pidfile: /tmp/pids/sidekiq.pid :logfile: log/sidekiq.log staging: :concurrency: 10 production: :concurrency: 20 queues: - default 

我之前没有看到在一把钥匙前面有一个冒号,但省略了冒号会产生有趣的结果。 对于:pidfile:例如,前面有冒号,它创建/覆盖没有它的目标文件,它使用已存在的目标文件而不写入它。

这是在某处记录的,还是Sidekiq对某些键的期望?

以冒号开头的YAML键在Ruby中生成符号化键,而没有冒号的键将生成字符串化键:

 require 'yaml' string =<<-END_OF_YAML :concurrency: 5 :pidfile: /tmp/pids/sidekiq.pid :logfile: log/sidekiq.log staging: :concurrency: 10 production: :concurrency: 20 queues: - default END_OF_YAML YAML.load(string) # { # :concurrency => 5, # :pidfile => "/tmp/pids/sidekiq.pid", # :logfile => "log/sidekiq.log", # "staging" => { # :concurrency => 10 # }, # "production" => { # :concurrency => 20 # }, # "queues" => [ # [0] "default" # ] # } 

注意:如果gem依赖于符号化键,则字符串化键不会覆盖其默认值。

它实际上不是sidekiq特定的。 键前面的冒号只是使该键成为符号而不是字符串:

 # example.yml a: value: 1 :b: value: 2 yaml = YAML.load_file('example.yml') yaml["a"] => { "value" => 1 } yaml[:b] => { "value" => 1 } 

因此,如果您的代码使用键符号访问配置,您应该在yaml文件中的键前添加冒号,或者使用#with_indifferent_access之类的一些键转换为结果哈希(在解析yaml文件之后)