Created
April 16, 2014 09:21
-
-
Save buren/10839809 to your computer and use it in GitHub Desktop.
Retry given block until response is not nil or max_retries is reached
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
class RetryableCall | |
DEFAULT_OPTIONS = { | |
sleep: 0.5, | |
max_retries: 5 | |
} | |
def self.perform options = {}, &block | |
new(options).perform(&block) | |
end | |
def initialize options = {} | |
@options = DEFAULT_OPTIONS.merge(options) | |
end | |
# Retries given block until not nil or max_retries is reached | |
# returns first non-nil object | |
def perform &block | |
response = nil | |
tries = 0 | |
while response.nil? | |
break if tries > @options[:max_retries] | |
response = block.call | |
tries += 1 | |
sleep @options[:sleep] | |
end | |
response | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment