ruby-on-rails 前面的冒号:YAML语法

7fyelxc5  于 2023-02-01  发布在  Ruby
关注(0)|答案(2)|浏览(106)

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

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

我以前没有见过在键前面有冒号的情况,但是省略冒号会产生有趣的结果。例如,在:pidfile:的情况下,如果前面有冒号,它会在没有冒号的地方创建/覆盖目标文件,它会使用已经存在的文件,而不会写入它。
这是在某个地方记录的,还是只是Sidekiq期望某些键的方式?

js4nwp54

js4nwp541#

以冒号开头的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依赖于符号化键时,字符串化键将不会覆盖其默认值。

ne5o7dgx

ne5o7dgx2#

它实际上并不是特定于sidekiq的,键前面的冒号只是使这个键成为一个符号而不是字符串:

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

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

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

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

相关问题