Skip to content

Instantly share code, notes, and snippets.

@adamesque
Created February 10, 2012 01:58
Show Gist options
  • Save adamesque/1785444 to your computer and use it in GitHub Desktop.
Save adamesque/1785444 to your computer and use it in GitHub Desktop.
SHA1 cache buster extension for Middleman 2.x
module Middleman::Features
# modeled after built-in CacheBuster extension
# appends truncated SHA1 hashes to the querystring of asset_url'd files.
module Sha1CacheBuster
require 'digest/sha1'
class << self
def registered(app)
app.set :sha1_asset_paths, []
app.send :include, InstanceMethods
app.after_build do
puts " Appending SHA1 cache busters…"
app.sha1_asset_paths.uniq!
# build the SHA1 digests
digests = app.sha1_asset_paths.map do |f|
build_path = File.expand_path(File.join(app.build_dir, f))
Digest::SHA1.hexdigest(File.read(build_path))[7..16]
end
Dir[File.join(app.build_dir, '**/*.{html,js,css}')].each do |f|
contents = File.read(f)
app.sha1_asset_paths.each_with_index do |path, i|
contents.gsub!(path, path + "?#{digests[i]}")
end
File.open(f, 'w') {|f| f.puts(contents) }
end
end
end
alias :included :registered
end
module InstanceMethods
def asset_url(path, prefix="")
settings.sha1_asset_paths << super
super
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment