Class: Mocloud::Utils::RedirectFollower

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

Defined Under Namespace

Classes: TooManyRedirects

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, limit = 5) ⇒ RedirectFollower

Returns a new instance of RedirectFollower.



10
11
12
# File 'lib/mocloud/utils/redirect_follower.rb', line 10

def initialize(url, limit=5)
  @url, @redirect_limit = url, limit
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



8
9
10
# File 'lib/mocloud/utils/redirect_follower.rb', line 8

def body
  @body
end

#redirect_limitObject

Returns the value of attribute redirect_limit.



8
9
10
# File 'lib/mocloud/utils/redirect_follower.rb', line 8

def redirect_limit
  @redirect_limit
end

#responseObject

Returns the value of attribute response.



8
9
10
# File 'lib/mocloud/utils/redirect_follower.rb', line 8

def response
  @response
end

#statusObject

Returns the value of attribute status.



8
9
10
# File 'lib/mocloud/utils/redirect_follower.rb', line 8

def status
  @status
end

#urlObject

Returns the value of attribute url.



8
9
10
# File 'lib/mocloud/utils/redirect_follower.rb', line 8

def url
  @url
end

Instance Method Details

#redirect_urlObject



39
40
41
42
43
44
45
# File 'lib/mocloud/utils/redirect_follower.rb', line 39

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

#resolveObject

Raises:



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/mocloud/utils/redirect_follower.rb', line 14

def resolve
  raise TooManyRedirects if redirect_limit < 0

		uri = URI.parse(self.url)

		http = Net::HTTP.new(uri.host, uri.port)
		http.use_ssl = true if uri.scheme == "https"  # enable SSL/TLS
		http.start do
http.request_get("#{uri.path}?#{uri.query}") do |res|
	self.response = res
end
		end

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

    resolve
  end

  self.body = response.body
  self.status = response.code
  self
end