Class: LinkThumbnailer::Fetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/link_thumbnailer/fetcher.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#urlObject

Returns the value of attribute url.



7
8
9
# File 'lib/link_thumbnailer/fetcher.rb', line 7

def url
  @url
end

Instance Method Details

#fetch(url, redirect_count = 0) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/link_thumbnailer/fetcher.rb', line 9

def fetch(url, redirect_count = 0)
  if redirect_count > LinkThumbnailer.configuration.redirect_limit
    raise ArgumentError, "too many redirects (#{redirect_count})"
  end

  self.url = url.is_a?(URI) ? url : URI(url)

  if self.url.is_a?(URI::HTTP)
    http                        = Net::HTTP::Persistent.new('linkthumbnailer')
    http.headers['User-Agent']  = LinkThumbnailer.configuration.user_agent
    http.verify_mode            = OpenSSL::SSL::VERIFY_NONE unless LinkThumbnailer.configuration.verify_ssl
    http.open_timeout           = LinkThumbnailer.configuration.http_timeout
    resp                        = http.request(self.url)
    case resp
    when Net::HTTPSuccess     then resp.body
    when Net::HTTPRedirection
      location = resp['location'].start_with?('http') ? resp['location'] : "#{self.url.scheme}://#{self.url.host}#{resp['location']}"
      fetch(location, redirect_count + 1)
    else resp.error!
    end
  end
end