Class: Ridley::Middleware::Retry

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/ridley/middleware/retry.rb

Overview

Note:

Borrowed and modified from: https://github.com/lostisland/faraday/blob/master/lib/faraday/request/retry.rb use the Faraday official middleware after the release of 0.9.x

Catches exceptions and retries each request a limited number of times.

Examples:


Faraday.new do |conn|
  conn.request :retry, max: 2, interval: 0.05, exceptions: [CustomException, Faraday::Timeout::Error]
  conn.adapter ...
end

Author:

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Retry

Returns a new instance of Retry

Parameters:

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :max (Integer)

    maximum number of retries

  • :interval (Float)

    pause in seconds between retries

  • :exceptions (Array)

    the list of exceptions to handle


22
23
24
25
26
# File 'lib/ridley/middleware/retry.rb', line 22

def initialize(app, options = {})
  super(app)
  @options  = options.slice(:max, :interval, :exceptions)
  @errmatch = build_exception_matcher(@options[:exceptions])
end

Instance Method Details

#build_exception_matcher(exceptions) ⇒ Object

construct an exception matcher object.

An exception matcher for the rescue clause can usually be any object that responds to `===`, but for Ruby 1.8 it has to be a Class or Module.


46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/ridley/middleware/retry.rb', line 46

def build_exception_matcher(exceptions)
  matcher = Module.new
  (class << matcher; self; end).class_eval do
    define_method(:===) do |error|
      exceptions.any? do |ex|
        if ex.is_a? Module then error.is_a? ex
        else error.class.to_s == ex.to_s
        end
      end
    end
  end
  matcher
end

#call(env) ⇒ Object


28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/ridley/middleware/retry.rb', line 28

def call(env)
  retries = @options[:max]
  begin
    @app.call(env)
  rescue @errmatch
    if retries > 0
      retries -= 1
      sleep @options[:interval] if @options[:interval] > 0
      retry
    end
    raise
  end
end