Skip to content

Instantly share code, notes, and snippets.

@atheiman
Last active November 28, 2017 14:32
Show Gist options
  • Save atheiman/33f870cf850358701a8dbd4fd965d5a2 to your computer and use it in GitHub Desktop.
Save atheiman/33f870cf850358701a8dbd4fd965d5a2 to your computer and use it in GitHub Desktop.
Execute a block with retries for exceptions
def doubles?
a = rand(1..6)
b = rand(1..6)
puts "#{a} and #{b}"
raise 'Not doubles!' unless a == b
true
end
def with_retries(retries: 2, sleep: 1)
attempt = 1
begin
puts "attempt #{attempt}"
value = yield
rescue LocalJumpError => e # error for no block given
raise e
rescue StandardError => e # all other errors
puts "attempt #{attempt} failed!"
if (attempt += 1) <= (retries + 1)
Kernel.sleep(sleep)
retry
end
raise e
end
puts "attempt #{attempt} succeeded!"
value
end
with_retries { doubles? }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment