Created
August 18, 2020 00:18
-
-
Save PandaWhisperer/42ae0aa1e02cdbe7047573f75b8ef598 to your computer and use it in GitHub Desktop.
Attempt n times
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
# 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