Class: MLB::RedirectHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/mlb/redirect_handler.rb

Constant Summary collapse

DEFAULT_MAX_REDIRECTS =
10

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection: Connection.new, request_builder: RequestBuilder.new, max_redirects: DEFAULT_MAX_REDIRECTS) ⇒ RedirectHandler

Returns a new instance of RedirectHandler.



14
15
16
17
18
19
# File 'lib/mlb/redirect_handler.rb', line 14

def initialize(connection: Connection.new, request_builder: RequestBuilder.new,
  max_redirects: DEFAULT_MAX_REDIRECTS)
  @connection = connection
  @request_builder = request_builder
  @max_redirects = max_redirects
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



12
13
14
# File 'lib/mlb/redirect_handler.rb', line 12

def connection
  @connection
end

#max_redirectsObject

Returns the value of attribute max_redirects.



11
12
13
# File 'lib/mlb/redirect_handler.rb', line 11

def max_redirects
  @max_redirects
end

#request_builderObject (readonly)

Returns the value of attribute request_builder.



12
13
14
# File 'lib/mlb/redirect_handler.rb', line 12

def request_builder
  @request_builder
end

Instance Method Details

#handle(response:, request:, base_url:, redirect_count: 0) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/mlb/redirect_handler.rb', line 21

def handle(response:, request:, base_url:, redirect_count: 0)
  if response.is_a?(Net::HTTPRedirection)
    raise TooManyRedirects, "Too many redirects" if redirect_count > max_redirects

    new_uri = build_new_uri(response, base_url)

    new_request = build_request(request, new_uri, Integer(response.code))
    new_response = connection.perform(request: new_request)

    handle(response: new_response, request: new_request, base_url:, redirect_count: redirect_count + 1)
  else
    response
  end
end