Created
June 14, 2010 18:40
-
-
Save mbailey/438077 to your computer and use it in GitHub Desktop.
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
# config/initializers/fingerprint.rb # XXX Breaks Rails asset bundling | |
# | |
# Mike Bailey <mike@bailey.net.au> | |
# | |
# Updates Rails Helpers to use fingerprint in path instead of timestamp in query string. | |
# | |
# Add the following to your Apache config to remove the fingerprints: | |
# | |
# # Remove fingerprints | |
# RewriteEngine On | |
# RewriteRule (.+?)-fp-\w+\.(css|js|gif|png|jpg)$ $1\.$2 [L] | |
# | |
# This is my attempt to write a super simple Fingerprinter for Rails assets to improve | |
# speed up my site by improving caching performance. Warning! I've not fully tested this. | |
# Read the code and decided for yourself whether it suits your purposes. | |
# | |
# Eliot Skyes brought the issue to my attention with his plugin http://bit.ly/cdkIXg | |
# I had a bit of trouble understanding how the plugin worked so decided to try writing | |
# my own version. | |
# | |
# Tim Lucas provided some great insights into the issues and solutions http://bit.ly/d9s4Lh | |
# | |
# Although this is piggy backing off the asset timestamps cache I'd like to implement a file | |
# based Fingerprint cache so that checksums can optionally be kept with the source. | |
require 'digest/md5' | |
module ActionView | |
module Helpers | |
module AssetTagHelper | |
# Use the RAILS_ASSET_ID environment variable or the source's | |
# modification time as its cache-busting asset id. | |
def rails_asset_id(source) | |
if asset_id = ENV["RAILS_ASSET_ID"] | |
asset_id | |
else | |
if @@cache_asset_timestamps && (asset_id = @@asset_timestamps_cache[source]) | |
asset_id | |
else | |
path = File.join(ActionView::Helpers::AssetTagHelper::ASSETS_DIR, source) | |
# Replace with fingerprint | |
# asset_id = File.exist?(path) ? File.mtime(path).to_i.to_s : '' | |
asset_id = fingerprint(path) | |
if @@cache_asset_timestamps | |
@@asset_timestamps_cache_guard.synchronize do | |
@@asset_timestamps_cache[source] = asset_id | |
end | |
end | |
asset_id | |
end | |
end | |
end | |
def fingerprint(source) | |
'-fp-' + Digest::MD5.hexdigest(File.open(source).read)[0,7] | |
end | |
def rewrite_asset_path(source, path=nil) | |
source.gsub(/(\..[^\/]+?)$/, rails_asset_id(source) + '\1') | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment