Skip to content

Instantly share code, notes, and snippets.

@Darksecond
Created January 11, 2016 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Darksecond/09cd855b0954390e718f to your computer and use it in GitHub Desktop.
Save Darksecond/09cd855b0954390e718f to your computer and use it in GitHub Desktop.
Favicon Microgem

Favicon Microgem

This fetches all known favicons for a url. It will return an array of hashes with a href, x and y. If the size is unknown it will return 0 for x and y

GEM::Specification.new do |gem|
gem.name = gem.summary = 'favicon'
gem.version = '1.0.0'
gem.files = ['favicon.rb']
gem.require_path = '.'
gem.authors = ['Tim Peters']
gem.add_dependency 'nokogiri', '~> 1.6.7'
gem.add_dependency 'httparty', '~> 0.13.7'
end
require 'nokogiri'
require 'httparty'
module Favicon
class Fetcher
include HTTParty
follow_redirects true
end
def self.get(url)
uri = Addressable::URI.heuristic_parse(url)
html = Fetcher.get(uri.to_s).body
doc = Nokogiri::HTML html
[
favicons = parse_icons(doc),
parse_shortcut_icons(doc),
fallback_icon(uri)
].flatten.sort { |y, x| x[:x] <=> y[:x] }
end
def self.parse_icons(doc)
doc.css('link[rel=icon]').map do |element|
{
href: element.attr('href'),
x: element.attr('sizes').split('x')[0].to_i,
y: element.attr('sizes').split('x')[1].to_i
}
end
end
def self.parse_shortcut_icons(doc)
doc.css('link[rel="shortcut icon"]').map do |element|
{
href: element.attr('href'),
x: 16,
y: 16
}
end
end
def self.fallback_icon(uri)
{
href: uri.join('favicon.ico').to_s,
x: 0,
y: 0,
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment