冒号在前面:YAML 语法
Colon in the front: YAML syntax
我目前在一个项目中使用 Sidekiq,我有以下 YAML 配置文件:
:concurrency: 5
:pidfile: /tmp/pids/sidekiq.pid
:logfile: log/sidekiq.log
staging:
:concurrency: 10
production:
:concurrency: 20
queues:
- default
我以前从未见过在键前面有冒号,但省略冒号会产生有趣的结果。例如,在 :pidfile:
的情况下,前面有冒号 creates/overrides 没有它的目标文件,它使用已经存在的文件并且不写入它。
这是否记录在某处,或者这仅仅是 Sidekiq 期望某些键的方式?
它实际上不是 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 文件)
以冒号开头的 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,我有以下 YAML 配置文件:
:concurrency: 5
:pidfile: /tmp/pids/sidekiq.pid
:logfile: log/sidekiq.log
staging:
:concurrency: 10
production:
:concurrency: 20
queues:
- default
我以前从未见过在键前面有冒号,但省略冒号会产生有趣的结果。例如,在 :pidfile:
的情况下,前面有冒号 creates/overrides 没有它的目标文件,它使用已经存在的文件并且不写入它。
这是否记录在某处,或者这仅仅是 Sidekiq 期望某些键的方式?
它实际上不是 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 文件)
以冒号开头的 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 依赖符号化键,则字符串化键不会覆盖其默认值。