Created
March 25, 2015 14:01
-
-
Save hamajyotan/6bf8e4e5856cf90603b7 to your computer and use it in GitHub Desktop.
block with retry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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