Class: HTTP::Redirector

Inherits:
Object
  • Object
show all
Defined in:
lib/http/redirector.rb

Overview

Follows HTTP redirects according to configured policy

Defined Under Namespace

Classes: EndlessRedirectError, TooManyRedirectsError

Constant Summary collapse

REDIRECT_CODES =

HTTP status codes which indicate redirects

[300, 301, 302, 303, 307, 308].to_set.freeze
STRICT_SENSITIVE_CODES =

Codes which which should raise StateError in strict mode if original request was any of UNSAFE_VERBS

[300, 301, 302].to_set.freeze
UNSAFE_VERBS =

Insecure http verbs, which should trigger StateError in strict mode upon STRICT_SENSITIVE_CODES

%i[put delete post].to_set.freeze
SEE_OTHER_ALLOWED_VERBS =

Verbs which will remain unchanged upon See Other response.

%i[get head].to_set.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(strict: true, max_hops: 5, on_redirect: nil) ⇒ HTTP::Redirector

Initializes a new Redirector

Examples:

HTTP::Redirector.new(strict: true, max_hops: 5)

Parameters:

  • strict (Boolean) (defaults to: true)

    (true) redirector hops policy

  • max_hops (#to_i) (defaults to: 5)

    (5) maximum allowed amount of hops

  • on_redirect (#call, nil) (defaults to: nil)

    optional redirect callback



56
57
58
59
60
# File 'lib/http/redirector.rb', line 56

def initialize(strict: true, max_hops: 5, on_redirect: nil)
  @strict      = strict
  @max_hops    = Integer(max_hops)
  @on_redirect = on_redirect
end

Instance Attribute Details

#max_hopsFixnum (readonly)

Returns maximum allowed hops

Examples:

redirector.max_hops # => 5

Returns:

  • (Fixnum)


44
45
46
# File 'lib/http/redirector.rb', line 44

def max_hops
  @max_hops
end

#strictBoolean (readonly)

Returns redirector policy

Examples:

redirector.strict # => true

Returns:

  • (Boolean)


35
36
37
# File 'lib/http/redirector.rb', line 35

def strict
  @strict
end

Instance Method Details

#perform(request, response) ⇒ HTTP::Response

Follows redirects until non-redirect response found

Examples:

redirector.perform(request, response) { |req| client.perform(req) }

Parameters:

Returns:



71
72
73
74
75
76
77
78
79
# File 'lib/http/redirector.rb', line 71

def perform(request, response, &)
  @request  = request
  @response = response
  @visited  = []

  follow_redirects(&) while REDIRECT_CODES.include?(@response.code)

  @response
end