Sha256: cb3aa5dc786dd7618a26b4cb59fa61c4d2c99b8905abb1b5e260103096359e4c

Contents?: true

Size: 970 Bytes

Versions: 2

Compression:

Stored size: 970 Bytes

Contents

require 'tries/version'
require 'gem_config'

module Tries
  include GemConfig::Base

  with_configuration do
    has :on_error, classes: Proc
  end
end

class Integer
  def tries(options = {}, &block)
    attempts          = 1
    exception_classes = Array(options[:on] || StandardError)
    delay             = options[:delay]
    incremental       = options[:incremental]

    begin
      return yield
    rescue *exception_classes => exception
      next_delay = calculate_delay(delay, attempts, incremental) if delay
      Tries.configuration.on_error.call(exception, attempts, next_delay) if Tries.configuration.on_error
      options[:on_error].call(exception, attempts, next_delay) if options[:on_error]
      Kernel.sleep next_delay if delay
      retry if (attempts += 1) <= self
    end

    yield
  end

  private
  def calculate_delay(delay, attempts, incremental)
    return delay unless incremental
    (delay * attempts * 100).round.to_f / 100
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
tries-0.3.2 lib/tries.rb
tries-0.3.1 lib/tries.rb