Class: EmbedFilter

Inherits:
Nanoc::Filter
  • Object
show all
Defined in:
lib/nanoc-embed.rb

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ EmbedFilter

Returns a new instance of EmbedFilter.



11
12
13
14
15
# File 'lib/nanoc-embed.rb', line 11

def initialize(hash={})
  super
  @cache_file = ".oembed_cache"
  @cache = open_cache
end

Instance Method Details

#get_oembed(url) ⇒ Object



34
35
36
37
38
39
# File 'lib/nanoc-embed.rb', line 34

def get_oembed(url)
  resource = OEmbed::Providers.get(url)
  resource.html
rescue OEmbed::NotFound => e
  url
end

#open_cacheObject



41
42
43
44
45
46
47
# File 'lib/nanoc-embed.rb', line 41

def open_cache
  if File.exists?(@cache_file)
    File.open(@cache_file) {|f| Marshal.load(f)}
  else
    Hash.new
  end
end

#run(content, params = {}) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/nanoc-embed.rb', line 17

def run(content, params={})
  urls = URI.extract(content, ['http', 'https'])
  content2 = content.dup
  urls.each do |url|
    html = @cache.fetch(url, nil)
    if html.nil?
      html = get_oembed(url)
    end
    if !html.nil?
      content2.gsub!(url, html)
    end
    @cache.store(url, html)
  end
  save_cache @cache
  content2
end

#save_cache(cache) ⇒ Object



49
50
51
# File 'lib/nanoc-embed.rb', line 49

def save_cache(cache)
  File.open(@cache_file, 'w') {|f| Marshal.dump(cache, f)}
end