如何将YAML序列转换为数组

时间:2016-11-23 18:37:46

标签: ruby-on-rails ruby yaml

我需要循环遍历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块之外构建该数组?

2 个答案:

答案 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"]}}