Skip to content

Instantly share code, notes, and snippets.

@buren
Created April 16, 2014 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buren/10839809 to your computer and use it in GitHub Desktop.
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
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