Skip to content

Instantly share code, notes, and snippets.

@PandaWhisperer
Created August 18, 2020 00:18
Show Gist options
  • Save PandaWhisperer/42ae0aa1e02cdbe7047573f75b8ef598 to your computer and use it in GitHub Desktop.
Save PandaWhisperer/42ae0aa1e02cdbe7047573f75b8ef598 to your computer and use it in GitHub Desktop.
Attempt n times
# Attempt a certain action several times before giving up
#
# Usage: `attempt(3.times, rescue: RuntimeError) do ... end`
#
def attempt(times, options = {})
times = times.is_a?(Enumerator) ? times.max : times.to_i
begin
attempt ||= 0
puts "Checking (attempt #{attempt+1})..."
sleep(attempt)
yield(attempt)
rescue options[:rescue] => ex
retry if (attempt += 1) <= times
puts "Giving up.".yellow
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment