Created
March 17, 2013 00:09
-
-
Save evansolomon/5178920 to your computer and use it in GitHub Desktop.
Capistrano task to version files via their names so that they are cacheable as possible (vs query strings). Bases versions on the file contents so that versions are changed as infrequently as possible, and automatically. Updates all references to the static files.
This file contains 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
namespace :build do | |
desc "Name static files by version" | |
task :version, :roles => :app do | |
find_static_files = "find #{current_release} -name '*.js' -o -name '*.css'" | |
capture(find_static_files).split("\n").each do |file| | |
# Get paths | |
full_path = file.chomp | |
relative_path = full_path.clone | |
relative_path["#{current_release}/"] = '' | |
# Build new file name based on hash | |
parts = relative_path.split "." | |
ext = parts.pop | |
hash = Digest::MD5.hexdigest(capture "cat #{full_path}") | |
new_relative_path = "#{parts.join('.')}.#{hash}.#{ext}" | |
# Rename the file | |
run "mv #{full_path} #{current_release}/#{new_relative_path}" | |
# Replace refereces to the file | |
search = Regexp.escape(relative_path).gsub "/", "\\/" | |
replace = Regexp.escape(new_relative_path).gsub "/", "\\/" | |
run "find #{current_release} -type f -exec perl -i -lpe 's/#{search}/#{replace}/g' {} \\;" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment