1

I need to loop through a YAML sequence and build an array with the sequence items.

I assume my YAML sequence should look like this in my config/redis:

redis:
  host:
  port:
  sentinels:
    - 1.34.79.100
    - 1.45.79.101
    - 1.46.79.102

In my config/initializers/sidekiq.rb I have a configure_client block that looks like:

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

I don't know how to dynamically load the listed Redis sentinels into that array. Do I need to build that array outside of the hash and configure_client block?

2

2 Answers 2

2

I would do something like this:

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
Sign up to request clarification or add additional context in comments.

2 Comments

You probably want load_file, not load. load expects a string containing the YAML to parse, whereas load_file wants a filename which it then reads and parses. Also, using config as the outer variable and also as the block's parameter isn't good practice.
@theTinMan You are right, thanks. I fixed my answer.
0

A YAML string can be converted back into Ruby data like so:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.