我需要循环遍历YAML序列并使用序列项构建数组。
我认为我的YAML序列应该在我的config/redis
:
redis:
host:
port:
sentinels:
- 1.34.79.100
- 1.45.79.101
- 1.46.79.102
在我的config/initializers/sidekiq.rb
我有configure_client
块看起来像:
Sidekiq.configure_client do |config|
config.redis = {
master_name: 'util-master'
sentinels: [
"sentinel://#{first_redis_sentinel}:23679"
"sentinel://#{second_redis_sentinel}:23679"
"sentinel://#{third_redis_sentinel}:23679"
],
failover_reconnect_timeout: 20,
url: "redis://#{redis_host}:6379/12" }
end
我不知道如何将列出的Redis标记动态加载到该数组中。我是否需要在哈希和configure_client
块之外构建该数组?
答案 0 :(得分:2)
我会做这样的事情:
require 'yaml'
redis_configuration = YAML.load_file(Rails.root.join('config', 'redis.yml'))
Sidekiq.configure_client do |config|
config.redis = {
master_name: 'util-master'
sentinels: redis_configuration['redis']['sentinels'].map { |sentinel|
"sentinel://#{sentinel}:23679"
},
failover_reconnect_timeout: 20,
url: "redis://#{redis_configuration['redis']['host']}:6379/12"
}
end
答案 1 :(得分:0)
可以将YAML字符串转换回Ruby数据,如下所示:
1.9.3-p551 :005 > yaml = <<YAML
1.9.3-p551 :006"> redis:
1.9.3-p551 :007"> host:
1.9.3-p551 :008"> port:
1.9.3-p551 :009"> sentinels:
1.9.3-p551 :010"> - 1.34.79.100
1.9.3-p551 :011"> - 1.45.79.101
1.9.3-p551 :012"> - 1.46.79.102
1.9.3-p551 :013"> YAML
=> "redis:\n host:\n port:\n sentinels:\n - 1.34.79.100\n - 1.45.79.101\n - 1.46.79.102\n"
1.9.3-p551 :014 > YAML.load(yaml)
=> {"redis"=>{"host"=>nil, "port"=>nil, "sentinels"=>["1.34.79.100", "1.45.79.101", "1.46.79.102"]}}