Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 保证无错误初始化的更好方法_Ruby_Mongodb - Fatal编程技术网

Ruby 保证无错误初始化的更好方法

Ruby 保证无错误初始化的更好方法,ruby,mongodb,Ruby,Mongodb,我的初始化随机失败 实现init的更好方法是什么 请至少重试10次 我找到了这样的解决办法 begin coll.insert( { "counter" => i, "named" => "name#{i}" }) rescue Mongo::ConnectionFailure => ex sleep(0.5) coll.insert( { "counter" => i, "named" => "name#{i}" }) end 有什么优雅

我的初始化随机失败

实现init的更好方法是什么

请至少重试10次

我找到了这样的解决办法

begin  
  coll.insert( { "counter" => i, "named" => "name#{i}" })
rescue Mongo::ConnectionFailure => ex  
  sleep(0.5)
  coll.insert( { "counter" => i, "named" => "name#{i}" })
end  

有什么优雅的方法可以做到这一点吗?因为我需要在我的项目中的许多地方执行类似的init,所以您可以将连接逻辑提取到另一个方法并执行以下操作

connections = 0
while connections < 10 # or however many
  begin
    try_connecting
    break # only called when no error raised
  rescue Mongo::ConnectionFailure => ex
    connections += 1
    sleep(0.5)
  end
end

按积木或产量计算,它能更优雅吗?我不认为积木是优雅的。它们很有用,并提供额外的定制,但这里不需要它们。我已经用另一次尝试更新了答案
connections = 0
while connections < 10 # or however many
  begin
    try_connecting
    break # only called when no error raised
  rescue Mongo::ConnectionFailure => ex
    connections += 1
    sleep(0.5)
  end
end
def connect
  try_connecting
rescue Mongo::ConnectionFailure => ex
  fail = true
  sleep(0.5)
ensure
  return defined?(fail)
end

10.times { break unless connect }