Ruby variable subsitution in method call

117 views Asked by At

Ruby noob here. Any help with a little issue I'm having would be appreciated. I am trying to place an array into a connection string argument which is formatted as an array.

My array is as follows:

hosts = ["192.168.0.2:27017","192.168.0.3:27017"]

I need to pull the array apart and structure it like an array so that I can substitute all of the connections into the call at once. The number of hosts can vary so hence why its in an array.

hosts_mapped = hosts.map { |i| "'" + i.to_s + "'" }.join(",")

gives me "192.168.0.2:27017","192.168.0.3:27017" as a string I think... or this may have mapped it back to an array as I get an error which looks like the one below after trying to initiate a connection.

@conn = Mongo::ReplSetConnection.new([hosts_mapped], :refresh_mode => :sync, :refresh_interval => 10)

Exception `Mongo::ConnectionFailure' at gems/mongo-1.7.0/lib/mongo/util/pool_manager.rb:282 - Cannot connect to a replica set using seeds '192.168.0.2:27017
Mongo::ConnectionFailure: Cannot connect to a replica set using seeds '192.168.0.2:27017

As you can see it only seems to reference the first entry. I need to hold this array in a configuration file so this is the reason it does not go directly into the connection string above. To me it seems I have mapped hosts_mapped back to an array, but if I puts hosts_mapped I get the string in the correct format.

"192.168.0.2:27017","192.168.0.3:27017"

A working connection string looks like:

@conn = Mongo::ReplSetConnection.new(["192.168.0.2:27017","192.168.0.3:27017"], :refresh_mode => :sync, :refresh_interval => 10)

Does anyone have any idea where I am going wrong here?

Full code to test:

#!/usr/bin/ruby -d 
require "mongo" 
hosts = ["192.168.0.2:27017","192.168.0.3:27017"] 
hosts_mapped = hosts.map {|i| "'" + i.to_s + "'" }.join(",") @conn =
Mongo::ReplSetConnection.new([hosts_mapped], :refresh_mode => :sync,:refresh_interval => 10)
2

There are 2 answers

1
Stefan On BEST ANSWER

According to the docs Mongo::ReplSetConnection.new can take an array:

Mongo::ReplSetConnection.new(['localhost:30000', 'localhost:30001'])

Since you already have an array, you can just pass it as the first parameter:

hosts = ["192.168.0.2:27017","192.168.0.3:27017"]
Mongo::ReplSetConnection.new(hosts)
1
saihgala On

you already have an array hosts = ["192.168.0.2:27017","192.168.0.3:27017"]

And if @conn = Mongo::ReplSetConnection.new(["192.168.0.2:27017","192.168.0.3:27017"], :refresh_mode => :sync, :refresh_interval => 10) works all you need to do is

@conn = Mongo::ReplSetConnection.new(hosts, :refresh_mode => :sync, :refresh_interval => 10)