Module: Libertree::Embedder

Defined in:
lib/libertree/embedder.rb

Class Method Summary collapse

Class Method Details

.autoembed(text) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/libertree/embedder.rb', line 21

def self.autoembed(text)
  urls = extract_urls(text)
  urls.each do |url|
    cached = Libertree::Model::EmbedCache[ url: url ]
    next  if cached

    Libertree::Model::Job.find_or_create(
      task: 'http:embed',
      params: {
        'url' => url
      }.to_json
    )
  end
end

.extract_urls(text) ⇒ Object



60
61
62
63
64
65
66
# File 'lib/libertree/embedder.rb', line 60

def self.extract_urls(text)
  Render.to_html_nodeset(text).
    xpath('.//a/@href').
    map {|href| href.value.strip}.
    uniq.
    find_all {|href| href =~ self.supported }
end

.get(url) ⇒ Object



17
18
19
# File 'lib/libertree/embedder.rb', line 17

def self.get(url)
  Libertree::Embedding::CustomProviders.get(url) || OEmbed::Providers.get(url, {width: 500}).html
end

.inject_objects(html) ⇒ Object

Parameters:

  • parsed (Nokogiri::HTML::DocumentFragment)

    HTML tree



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/libertree/embedder.rb', line 37

def self.inject_objects(html)
  # extract every URL from a paragraph and append embed object if supported
  html.css('p').each do |p|
    # collect urls, ignore relative links
    urls = p.xpath(".//a[not(starts-with(@href,'/'))]/@href").map(&:value).reverse
    urls.each do |url|
      cached = Libertree::Model::EmbedCache.
        s("SELECT * FROM embed_cache WHERE url IN (?,?)", url, url.gsub('&', '&'))

      if cached[0]
        p.add_next_sibling("<div class='embed'>#{cached[0][:object]}</div>")
      end
    end
  end
  html
end

.supportedObject



54
55
56
57
58
# File 'lib/libertree/embedder.rb', line 54

def self.supported
  @supported ||= Regexp.union(
    OEmbed::Providers.urls.keys.concat Libertree::Embedding::CustomProviders.urls.keys
  )
end