Created
February 10, 2012 01:58
-
-
Save adamesque/1785444 to your computer and use it in GitHub Desktop.
SHA1 cache buster extension for Middleman 2.x
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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