Module: LongURL::Direct

Defined in:
lib/longurl/direct.rb

Class Method Summary collapse

Class Method Details

.follow_redirections(orig, limit = 5) ⇒ Object

Will follow redirections given url orig.

Exceptions

  • LongURL::NetworkError in case of a network error (timeout, socket error, …)

  • LongURL::InvalidURL in case of a bad url (nil, empty, not http scheme …)

  • LongURL::TooManyRedirections if there are too many redirection for destination



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/longurl/direct.rb', line 12

def self.follow_redirections(orig, limit = 5)
  raise LongURL::TooManyRedirections if limit == 0
  uri = LongURL::URL.check(orig)
  Net::HTTP.start(uri.host, uri.port) do |http|
    answer = http.get(uri.path.empty? ? '/' : uri.path)
    dest = answer['Location']
    (dest && dest[0, 7] == 'http://' && follow_redirections(dest, limit - 1)) || orig
  end
rescue Timeout::Error, Errno::ENETUNREACH, Errno::ETIMEDOUT, SocketError
  raise LongURL::NetworkError
rescue
  raise LongURL::UnknownError
end