Skip to content

Instantly share code, notes, and snippets.

@dkam
Last active December 15, 2023 07:51
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 dkam/285d0fb9fd0b9933f5220fe0bf7f7331 to your computer and use it in GitHub Desktop.
Save dkam/285d0fb9fd0b9933f5220fe0bf7f7331 to your computer and use it in GitHub Desktop.
Get a site's favicon
class Favicon
def initialize(doc, url: nil)
@doc = doc
@url = if url
@url = URI(url.to_s)
elsif canonical
URI(canonical)
else
URI("")
end
end
def get
URI(best).host.nil? ? @url.tap {|u| u.path = best }.to_s : best
end
def best = return apple_touch || apple_touch_precomposed || rel_icons || rel_icon || default
def canonical = @canonical ||= @doc.at_xpath("//link[@rel='canonical']/@href")&.value
def apple_touch_precomposed = @doc.at_xpath("//link[@rel='apple-touch-icon-precomposed']/@href")&.value
def apple_touch = @doc.at_xpath("//link[@rel='apple-touch-icon']/@href")&.value
def rel_icon = @doc.at_xpath("//link[@rel='icon' and not(@sizes)]/@href")&.value
def rel_icons
@doc.xpath("//link[@rel='icon' and (@sizes)]").max_by do |ele|
ele['sizes'].split("x").map(&:to_i).then { |a| a.length == 2 ? a[0] * a[1] : nil }
end.tap {|ele| ele&.dig('href') }
end
def default = @url.nil? ? nil : "#{@url}/favicon.ico"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment