middleman/middleman-more/lib/middleman-more/extensions/cache_buster.rb

74 lines
2.4 KiB
Ruby
Raw Normal View History

2011-12-31 23:28:17 +01:00
# Extension namespace
module Middleman::Extensions
2011-12-31 23:28:17 +01:00
# The Cache Buster extension
module CacheBuster
2011-12-31 23:28:17 +01:00
# Setup extension
class << self
2011-12-31 23:28:17 +01:00
# Once registered
def registered(app)
2011-12-31 23:28:17 +01:00
# Add instance methods to context
app.send :include, InstanceMethods
2011-12-31 23:28:17 +01:00
# After compass is setup, make it use the registered cache buster
app.compass_config do |config|
config.asset_cache_buster do |path, real_path|
real_path = real_path.path if real_path.is_a? File
2011-11-24 06:59:53 +01:00
real_path = real_path.gsub(File.join(root, build_dir), source)
if File.readable?(real_path)
File.mtime(real_path).strftime("%s")
else
$stderr.puts "WARNING: '#{File.basename(path)}' was not found (or cannot be read) in #{File.dirname(real_path)}"
end
end
end
end
alias :included :registered
end
2011-12-31 23:28:17 +01:00
# Cache buster instance methods
module InstanceMethods
2011-12-31 23:28:17 +01:00
# asset_url override if we're using cache busting
# @param [String] path
# @param [String] prefix
def asset_url(path, prefix="")
http_path = super
if http_path.include?("://") || !%w(.css .png .jpg .jpeg .svg .svgz .js .gif).include?(File.extname(http_path))
http_path
else
begin
prefix = images_dir if prefix == http_images_path
rescue
end
real_path_static = File.join(prefix, path)
if build?
real_path_dynamic = File.join(build_dir, prefix, path)
real_path_dynamic = File.expand_path(real_path_dynamic, root)
http_path << "?" + File.mtime(real_path_dynamic).strftime("%s") if File.readable?(real_path_dynamic)
2012-04-04 19:26:07 +02:00
elsif resource = sitemap.find_resource_by_path(real_path_static)
if !resource.template?
http_path << "?" + File.mtime(resource.source_file).strftime("%s")
else
# It's a template, possible with partials. We can't really know when
# it's updated, so generate fresh cache buster every time durin
# developement
http_path << "?" + Time.now.strftime("%s")
end
end
http_path
end
end
end
end
2011-12-31 23:28:17 +01:00
# Register the extension
# register :cache_buster, CacheBuster
end