Class: Ogo::Utils::RedirectFollower

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

Defined Under Namespace

Classes: EmptyURLError, TooManyRedirects

Constant Summary collapse

REDIRECT_DEFAULT_LIMIT =
5

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of RedirectFollower.

Raises:



13
14
15
16
17
18
# File 'lib/ogo/utils/redirect_follower.rb', line 13

def initialize(url, options = {})
  raise EmptyURLError if url.to_s.empty?
  @redirect_limit = options[:limit] || REDIRECT_DEFAULT_LIMIT
  @headers = options[:headers] || {}
  @url = url.start_with?('http') ? url : "http://#{url}"
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



11
12
13
# File 'lib/ogo/utils/redirect_follower.rb', line 11

def body
  @body
end

#charsetObject

Returns the value of attribute charset.



11
12
13
# File 'lib/ogo/utils/redirect_follower.rb', line 11

def charset
  @charset
end

#headersObject

Returns the value of attribute headers.



11
12
13
# File 'lib/ogo/utils/redirect_follower.rb', line 11

def headers
  @headers
end

#redirect_limitObject

Returns the value of attribute redirect_limit.



11
12
13
# File 'lib/ogo/utils/redirect_follower.rb', line 11

def redirect_limit
  @redirect_limit
end

#responseObject

Returns the value of attribute response.



11
12
13
# File 'lib/ogo/utils/redirect_follower.rb', line 11

def response
  @response
end

#urlObject

Returns the value of attribute url.



11
12
13
# File 'lib/ogo/utils/redirect_follower.rb', line 11

def url
  @url
end

Instance Method Details

#redirect_urlObject



51
52
53
54
55
56
57
# File 'lib/ogo/utils/redirect_follower.rb', line 51

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

#resolveObject

Raises:



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/ogo/utils/redirect_follower.rb', line 20

def resolve
  raise TooManyRedirects if redirect_limit < 0

  uri = Addressable::URI.parse(url).normalize

  http = Net::HTTP.new(uri.host, uri.inferred_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

  charset = nil
  if content_type = response['content-type']
    if content_type =~ /charset=(.+)/i
      charset = $1
    end
  end
  self.charset = charset

  self.body = response.body
  self
end