Skip to content

Instantly share code, notes, and snippets.

@karlseguin
Created October 24, 2010 15:50
Show Gist options
  • Save karlseguin/643625 to your computer and use it in GitHub Desktop.
Save karlseguin/643625 to your computer and use it in GitHub Desktop.
add cache-busting to images within stylesheets
require 'zlib'
@@cssPath = '../public/stylesheets/' #relative to where the script is running
@@imagePath = '../public/images/' #relative to where the script is running
@@styleSheets = ['myCssFile1.css', 'AntherCssFile.css']
def crc(fileName)
fileName = @@imagePath + fileName.slice(10..-1)
contents = File.read(fileName) ; nil
Zlib.crc32(contents,0).to_s(16)
end
@@styleSheets.each do |css|
fileName = @@cssPath + css
file = File.new(fileName, 'r')
lines = []
while line = file.gets
line.gsub! /\.\.\/images\/.*?\.(gif|jpg|png)(\?[a-z\d]+)?/ do |match|
queryIndex = match.index("?")
match = match.slice(0..queryIndex-1) unless queryIndex.nil?
match + "?" + crc(match)
end
lines << line
end
file.close
file = File.new(fileName, File::WRONLY|File::TRUNC)
lines.each {|line| file.puts line }
file.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment