Sha256: 2e8a092ca47c35f34072393ac0c45a2dc8dee31cbf5ee4571e8f5efb167882cf

Contents?: true

Size: 1.11 KB

Versions: 7

Compression:

Stored size: 1.11 KB

Contents

module Tins
  module Attempt
    def attempt(opts = {}, &block)
      sleep           = nil
      exception_class = StandardError
      if Numeric === opts
        attempts = opts
      else
        attempts        = opts[:attempts] || 1
        exception_class = opts[:exception_class] if opts.key?(:exception_class)
        sleep           = opts[:sleep]
      end
      return if attempts <= 0
      count = 0
      if exception_class.nil?
        begin
          count += 1
          if block.call(count)
            return true
          elsif count < attempts
            sleep_duration(sleep, count)
          end
        end until count == attempts
        false
      else
        begin
          count += 1
          block.call(count)
          true
        rescue exception_class
          if count < attempts
            sleep_duration(sleep, count)
            retry
          end
          false
        end
      end
    end

    private

    def sleep_duration(duration, count)
      case duration
      when Numeric
        sleep duration
      when Proc
        sleep duration.call(count)
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
tins-0.3.6 lib/tins/attempt.rb
tins-0.3.5 lib/tins/attempt.rb
tins-0.3.4 lib/tins/attempt.rb
tins-0.3.3 lib/tins/attempt.rb
tins-0.3.2 lib/tins/attempt.rb
tins-0.3.1 lib/tins/attempt.rb
tins-0.3.0 lib/tins/attempt.rb