Sha256: 58bdda368ce149f08ece0924447c319ae7eb1fdcb497ce235ccfd57cb2d63777

Contents?: true

Size: 926 Bytes

Versions: 2

Compression:

Stored size: 926 Bytes

Contents

# frozen_string_literal: true

# Exponential backoff retry wrapper
class ExpRetry
  attr_accessor :retries
  attr_reader :exception, :tried

  def self.for(retries: 3, exception: StandardError, verbose: false)
    new(retries: retries, exception: exception, verbose: verbose).call { yield }
  end

  def initialize(retries: 3, exception: StandardError, wait: 1000, verbose: false)
    @retries = retries
    @tried = 0
    @exception = exception
    @verbose = verbose
    @wait = wait
  end

  def call
    yield if block_given?
  rescue *@exception => e
    check(e)
    retry
  end

private

  def check(exception)
    raise(exception) if tried >= retries

    increment
    delay
  end

  def increment
    @tried += 1
  end

  def delay
    output = "*** #{@exception}. Retrying in #{time} seconds..."
    @verbose ? puts(output) : print('-')
    sleep time
  end

  def time
    2**tried * (@wait.to_f / 1000)
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
exp_retry-0.0.14 lib/exp_retry.rb
exp_retry-0.0.13 lib/exp_retry.rb