Class: Webstract::Favicon
- Inherits:
-
Object
- Object
- Webstract::Favicon
- Defined in:
- lib/webstract/favicon.rb
Instance Attribute Summary collapse
-
#data ⇒ Object
Returns the value of attribute data.
-
#url ⇒ Object
Returns the value of attribute url.
Class Method Summary collapse
Instance Method Summary collapse
- #fetch ⇒ Object
- #fetch_and_save(path) ⇒ Object
-
#initialize(options = {}) ⇒ Favicon
constructor
A new instance of Favicon.
Constructor Details
#initialize(options = {}) ⇒ Favicon
Returns a new instance of Favicon.
10 11 12 13 |
# File 'lib/webstract/favicon.rb', line 10 def initialize( = {}) raise(ArgumentError.new("requires url")) unless .key?(:url) @url = [:url] end |
Instance Attribute Details
#data ⇒ Object
Returns the value of attribute data.
8 9 10 |
# File 'lib/webstract/favicon.rb', line 8 def data @data end |
#url ⇒ Object
Returns the value of attribute url.
8 9 10 |
# File 'lib/webstract/favicon.rb', line 8 def url @url end |
Class Method Details
.get(url) ⇒ Object
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 54 55 56 57 58 59 60 61 62 |
# File 'lib/webstract/favicon.rb', line 27 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, allow_redirections: :all)) 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, allow_redirections: :all) unless stream.content_type[/^image/] raise(Errors::InvalidFavicon, "wrong content_type (#{stream.content_type})") end data = stream.read if data.size == 0 raise(Errors::InvalidFavicon, "zero data") end fav = Favicon.new(url: fav_uri.to_s) fav.data = data return fav rescue OpenURI::HTTPError => e raise Errors::MissingFavicon if e.to_s[/404/] raise # nevermind, reraise the previous exception end end |
Instance Method Details
#fetch ⇒ Object
15 16 17 |
# File 'lib/webstract/favicon.rb', line 15 def fetch @data = self.class.get(url).data end |
#fetch_and_save(path) ⇒ Object
19 20 21 22 23 24 25 |
# File 'lib/webstract/favicon.rb', line 19 def fetch_and_save(path) data = fetch File.open(path, 'w') do |f| f.write(data) f.close end end |