Sha256: d9968f391e2966ee6e8f8a48350ec39845eacf253a9805593c4a90a857ba79f5

Contents?: true

Size: 1.11 KB

Versions: 8

Compression:

Stored size: 1.11 KB

Contents

module Spruz
  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

8 entries across 8 versions & 1 rubygems

Version Path
spruz-0.2.13 lib/spruz/attempt.rb
spruz-0.2.12 lib/spruz/attempt.rb
spruz-0.2.11 lib/spruz/attempt.rb
spruz-0.2.10 lib/spruz/attempt.rb
spruz-0.2.9 lib/spruz/attempt.rb
spruz-0.2.8 lib/spruz/attempt.rb
spruz-0.2.7 lib/spruz/attempt.rb
spruz-0.2.6 lib/spruz/attempt.rb