Module: Faviconduit

Defined in:
lib/faviconduit.rb

Defined Under Namespace

Classes: Error, Favicon, InvalidFavicon, MissingFavicon

Class Method Summary collapse

Class Method Details

.get(url) ⇒ Object



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
# File 'lib/faviconduit.rb', line 16

def self.get(url)

  uri = Addressable::URI.heuristic_parse(url)
  uri = Addressable::URI.encode(uri) # needed for chars with accents in url

  doc = Nokogiri::HTML(open(uri))

  path = doc.xpath("//link[@rel='shortcut icon' or @rel='icon']/@href").first
  path = path ? path.to_s : '/favicon.ico'

  fav_uri = Addressable::URI.join(uri, path.to_s)

  begin

    stream = open(fav_uri)

    unless stream.content_type[/^image/]
      raise(InvalidFavicon, "wrong content_type (#{stream.content_type})")
    end

    data = stream.read

    if data.size == 0
      raise(InvalidFavicon, "zero data")
    end

    fav = Favicon.new
    fav.url = fav_uri.to_s
    fav.data = data
    return fav

  rescue OpenURI::HTTPError => e
    raise MissingFavicon if e.to_s[/404/]
    raise # nevermind, reraise the previous exception
  end

end