module Kernel
Public Instance Methods
rescue_up_to(times, from: StandardError, with: nil rescued_times = 0) { |rescued_times| ... }
click to toggle source
Rescues / retries a block, up to times
times.
Examples¶ ↑
# Rescue / retry something, up to 10 times value = rescue_up_to(10.times) do # do something, retry on StandardError... end # A more complex / useful example, fetch Google's home page require 'open-uri' contents = rescue_up_to(10.times, from: SocketError, with: ->(rescued_times){sleep rescued_times} ) do open('http://www.google.com').read end # => "[...]"
# File lib/rescue_up_to.rb 22 def rescue_up_to times, from: StandardError, with: nil # :yields: rescued_times 23 rescued_times = 0 24 times.each do 25 begin 26 return yield rescued_times 27 rescue *from => e 28 rescued_times += 1 29 with && (with.arity == 0 ? with.call : with.call(rescued_times)) 30 end 31 end 32 yield rescued_times 33 end