Class: UrlResolver::Resolver

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

Instance Method Summary collapse

Instance Method Details

#cacheObject



5
6
7
# File 'lib/url_resolver/resolver.rb', line 5

def cache
  UrlResolver.configuration.url_cache
end

#resolve(url) ⇒ Object



13
14
15
16
17
18
19
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
50
51
52
53
# File 'lib/url_resolver/resolver.rb', line 13

def resolve(url)
  url_to_check = URI.escape(url)
  cached_url = cache.get_url(url_to_check)
  return cached_url if cached_url
  
  response = RestClient.head(url_to_check, user_agent: user_agent)
  response.args[:url].tap do |final_url|
    cache.set_url(url_to_check, final_url)
  end
rescue SocketError,
  Errno::ETIMEDOUT,
  Errno::ECONNREFUSED,
  Errno::ECONNRESET,
  RestClient::InternalServerError,
  RestClient::ServiceUnavailable,
  RestClient::BadRequest,
  RestClient::GatewayTimeout,
  RestClient::RequestTimeout,
  RestClient::ResourceNotFound,
  RestClient::BadGateway,
  RestClient::MethodNotAllowed,
  RestClient::Unauthorized,
  RestClient::Forbidden,
  RestClient::NotAcceptable,
  URI::InvalidURIError => e
  
  if e.message == 'getaddrinfo: nodename nor servname provided, or not known'
    response = RestClient.head(url_to_check) { |response, request, result, &block| response }
    url = response.headers[:location] if response.code == 302 && response.headers[:location]
  end
  
  cache.set_url(url_to_check, url) if UrlResolver.configuration.cache_failures
  url
rescue Exception => e
  if e.message =~ /undefined method `request_uri'/
    cache.set_url(url_to_check, url) if UrlResolver.configuration.cache_failures
    url
  else
    raise UrlResolverError.new("#{e.class.to_s}: #{url} (#{e.message})")
  end
end

#user_agentObject



9
10
11
# File 'lib/url_resolver/resolver.rb', line 9

def user_agent
  UrlResolver.configuration.user_agent
end