Colon in the front: YAML syntax

一曲冷凌霜 提交于 2019-12-20 17:43:09

问题


I'm currently using Sidekiq in a project and I have the following YAML config file:

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

I haven't seen having a colon in front of a key before but omitting that colon produces interesting results. In the case of the :pidfile: for example, with the colon in front it creates/overrides the destination file where is without it, it uses the one already there and does not write to it.

Is this documented somewhere or is this simply how Sidekiq expects certain keys?


回答1:


YAML keys starting with a colon generate symbolized keys in Ruby, whereas keys without a colon will generate stringified keys:

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"
#     ]
# }

Note: If a gem depends on symbolized keys then the stringified keys will not override its defaults.




回答2:


It is actually not sidekiq specific. The colon in front of a key just makes this key a symbol instead of a string:

# example.yml
a:
  value: 1
:b:
  value: 2


yaml = YAML.load_file('example.yml')

yaml["a"] => { "value" => 1 }
yaml[:b] => { "value" => 1 }

So if your code accesses the config with key symbols, you should either add a colon in front of the key in the yaml file, or use some conversion of keys like #with_indifferent_access for the result hash (after parsing the yaml file)



来源:https://stackoverflow.com/questions/31673857/colon-in-the-front-yaml-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!