Module: LinkThumbnail

Defined in:
lib/link_thumbnail.rb,
lib/link_thumbnail/version.rb

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.fetch(url) ⇒ Object



54
55
56
# File 'lib/link_thumbnail.rb', line 54

def fetch(url)
  open(url).read
end

.thumbnail_url(url) ⇒ Object



9
10
11
12
13
14
15
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/link_thumbnail.rb', line 9

def thumbnail_url(url)
  source = open(url).read
  doc = Nokogiri.parse(source)

  if element = doc.xpath('//meta[@property="og:image" and @content]').first
    # OpenGraph
    return element.attributes['content'].value

  elsif element = doc.xpath('//link[@type="application/json+oembed" and @href]').first
    # oEmbed (JSON)
    oembed_json_response = fetch(element.attributes['href'].value)
    json = JSON.parse(oembed_json_response)
    if src = json['thumbnail_url']
      # Thumbnail (generic)
      return src
    elsif json['type'] == 'photo'
      # Photo type
      return json['url']
    end

  elsif element = doc.xpath('//link[@type="text/xml+oembed" and @href]').first
    # oEmbed (JSON)
    oembed_xml_response = fetch(element.attributes['href'].value)
    response = Nokogiri.parse(oembed_xml_response)
    if thumbnail = response.xpath('/oembed/thumbnail_url').first
      # Thumbnail (generic)
      return thumbnail.content
    elsif response.xpath('/oembed[type="photo" and url]').first
      # Photo type
      return response.xpath('/oembed/url').first.content
    end
  elsif element = doc.xpath('//img[@class="photo" and @src]').first
      # Microformat
      return element.attributes['src'].value

  elsif readability_doc = Readability::Document.new(source)
    # Semantic
    if element = readability_doc.get_best_candidate
      if img = element.xpath('//img[@src]').first
        return img.attributes['src'].value
      end
    end
  end
end