Skip to content

Instantly share code, notes, and snippets.

@grobie
Created March 18, 2017 19:07
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 grobie/f6399405a879f2d473a00f134e2ea301 to your computer and use it in GitHub Desktop.
Save grobie/f6399405a879f2d473a00f134e2ea301 to your computer and use it in GitHub Desktop.
Nanoc4 cache buster
# lib/filters/cache_buster.rb
require 'digest/sha1'
module CacheBuster
def self.fingerprint(item)
return 'dev' if ENV['NANOC_ENV'] == 'dev'
content = item.binary? ? File.read(item[:filename]) : item.raw_content
Digest::SHA1.hexdigest(content)[0..15]
end
def self.path(item)
item.identifier.without_ext + '-' + fingerprint(item) + '.' + item.identifier.ext
end
class Filter < ::Nanoc::Filter
identifier :cache_buster
def run(content, options = {})
dir = options[:directory] || File::Separator
regex = options[:regex] || regex(dir)
replacements = path_replacements(File.join(dir, '**', '*'))
content.gsub(regex) do |match|
replacements[match] || match
end
end
private
def regex(dir)
dir += File::Separator unless dir.end_with?(File::Separator)
parts = [dir, "([a-z0-9\\-_.]+#{File::Separator})*", '[a-z0-9\-_.]+']
/#{parts.join('')}/
end
def path_replacements(pattern)
@_path_replacements ||= {}
@_path_replacements[pattern] = begin
items.find_all(pattern).each_with_object({}) do |item, memo|
memo[item.identifier.to_s] = item.path
end
end
end
end
end
# Rules
# Write asset files to new location including file hash. Also rewrite paths in CSS/text files.
compile '/assets/*' do
unless item.binary?
filter :cache_buster, directory: '/assets/'
end
write CacheBuster.path(item)
end
# Example compilation rules for markdown files.
compile '/**/*.md' do
filter :erb
filter :redcarpet, options: {filter_html: true, autolink: true, no_intraemphasis: true, fenced_code_blocks: true, gh_blockcode: true, tables: true}, renderer_options: {with_toc_data: true}
filter :bootstrappify
layout '/default.html'
# Make sure to call the cache buster filter at the very end, so it can rewrite paths in layouts.
filter :cache_buster, directory: '/assets/'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment