Class: RedirectFollower

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

Defined Under Namespace

Classes: TooManyRedirects

Constant Summary collapse

REDIRECT_DEFAULT_LIMIT =
5

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, limit = REDIRECT_DEFAULT_LIMIT, options = {}) ⇒ RedirectFollower


9
10
11
12
13
14
15
16
# File 'lib/redirect_follower.rb', line 9

def initialize(url, limit = REDIRECT_DEFAULT_LIMIT, options = {})
  if limit.is_a? Hash
    options = limit
    limit = REDIRECT_DEFAULT_LIMIT
  end
  @url, @redirect_limit = url, limit
  @headers = options[:headers] || {}
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body


7
8
9
# File 'lib/redirect_follower.rb', line 7

def body
  @body
end

#headersObject

Returns the value of attribute headers


7
8
9
# File 'lib/redirect_follower.rb', line 7

def headers
  @headers
end

#redirect_limitObject

Returns the value of attribute redirect_limit


7
8
9
# File 'lib/redirect_follower.rb', line 7

def redirect_limit
  @redirect_limit
end

#responseObject

Returns the value of attribute response


7
8
9
# File 'lib/redirect_follower.rb', line 7

def response
  @response
end

#urlObject

Returns the value of attribute url


7
8
9
# File 'lib/redirect_follower.rb', line 7

def url
  @url
end

Instance Method Details

#redirect_urlObject


41
42
43
44
45
46
47
# File 'lib/redirect_follower.rb', line 41

def redirect_url
  if response['location'].nil?
    response.body.match(/<a href=\"([^>]+)\">/i)[1]
  else
    response['location']
  end
end

#resolveObject

Raises:


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/redirect_follower.rb', line 18

def resolve
  raise TooManyRedirects if redirect_limit < 0

  uri = URI.parse(URI.escape(url))

  http = Net::HTTP.new(uri.host, uri.port)
  if uri.scheme == 'https'
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_PEER
  end

  self.response = http.request_get(uri.request_uri, @headers)

  if response.kind_of?(Net::HTTPRedirection)
    self.url = redirect_url
    self.redirect_limit -= 1
    resolve
  end

  self.body = response.body
  self
end