Class: Columbus::RedirectFollower

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

Defined Under Namespace

Classes: TooManyRedirects

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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



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

def initialize(url, options={})
  @url = url
  @redirect_limit = options.delete(:limit) || 5
  logger.level = options.delete(:level) || Logger::WARN
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



5
6
7
# File 'lib/columbus/redirect_follower.rb', line 5

def body
  @body
end

#redirect_limitObject

Returns the value of attribute redirect_limit.



5
6
7
# File 'lib/columbus/redirect_follower.rb', line 5

def redirect_limit
  @redirect_limit
end

#responseObject

Returns the value of attribute response.



5
6
7
# File 'lib/columbus/redirect_follower.rb', line 5

def response
  @response
end

#urlObject

Returns the value of attribute url.



5
6
7
# File 'lib/columbus/redirect_follower.rb', line 5

def url
  @url
end

Instance Method Details

#loggerObject



13
14
15
# File 'lib/columbus/redirect_follower.rb', line 13

def logger
  @logger ||= Logger.new(STDOUT)
end

#redirect_urlObject



38
39
40
41
42
43
44
# File 'lib/columbus/redirect_follower.rb', line 38

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

#resolveObject

Raises:



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

def resolve
  raise TooManyRedirects if redirect_limit < 0
  
  self.response = Net::HTTP.get_response(URI.parse(url))

  logger.info "redirect limit: #{redirect_limit}" 
  logger.info "response code: #{response.code}" 
  logger.debug "response body: #{response.body}" 

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

    logger.info "redirect found, headed to #{url}" 
    resolve
  end

  self.body = response.body
  self
end