Skip to content

Instantly share code, notes, and snippets.

@hamajyotan
Created March 25, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamajyotan/6bf8e4e5856cf90603b7 to your computer and use it in GitHub Desktop.
Save hamajyotan/6bf8e4e5856cf90603b7 to your computer and use it in GitHub Desktop.
block with retry
def with_retry times: 2, catch: StandardError
yield binding.local_variable_defined?(:tries) ? binding.local_variable_get(:tries).to_i : 0
rescue *catch
raise unless (tries = tries.to_i + 1) < times
retry
end
# or
def with_retry times: 2, catch: StandardError
tries = 0
begin
yield tries
rescue *catch
raise unless (tries += 1) < times
retry
end
end
class FooError < RuntimeError; end
puts
puts "-" * 80
begin
with_retry do |i|
puts i
raise StandardError
end
rescue
puts $!
end
puts
puts "-" * 80
begin
with_retry times: 5 do |i|
puts i
raise StandardError
end
rescue
puts $!
end
puts
puts "-" * 80
begin
with_retry catch: [FooError, ArgumentError] do |i|
puts i
raise StandardError
end
rescue
puts $!
end
puts
puts "-" * 80
begin
with_retry times: 50 do |i|
puts i
raise StandardError if i < 3
end
rescue
puts $!
end
# --------------------------------------------------------------------------------
# 0
# 1
# StandardError
#
# --------------------------------------------------------------------------------
# 0
# 1
# 2
# 3
# 4
# StandardError
#
# --------------------------------------------------------------------------------
# 0
# StandardError
#
# --------------------------------------------------------------------------------
# 0
# 1
# 2
# 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment