Search code examples
sprocketsmiddleman

Middleman sprockets fingerprint


I'm using middleman with sprockets for packaging my js and css files into one file. This works fine. But I was wondering if it is possible to enable the fingerprint feature from sprockets in middleman.

e.g. my file all.js, in which everything gets compiled, gets renamed to all-4e17d33ff76d744900c2691a71ed83e4.js.

It would also be great, if this would be possible with images.


Solution

  • I haven't found a out of the box solution for this, but I made my own solution. In the config.rb I'm running the after_build hook. Not the best way, but it works:

    after_build do
      require 'fileutils'
      delete_except "build/javascripts/", "all.js"
      delete_except "build/stylesheets/", "all.css"
    
      require 'digest/sha1'
      sha1 = Digest::SHA1.hexdigest Time.now.getutc.to_i.to_s
      allJS = "all-" + sha1 + ".js"
      allCSS = "all-" + sha1 + ".css"
      File.rename("build/javascripts/all.js", "build/javascripts/" + allJS)
      File.rename("build/stylesheets/all.css", "build/stylesheets/" + allCSS)
    
      index_file = "build/index.html"
      html = File.read(index_file)
      html = html.gsub(/all\.js/, allJS)
      html = html.gsub(/all\.css/, allCSS)
    
      File.open(index_file, "w") { |file| file.puts html }
    end
    

    I'm doing the following:

    • delete unnecessary generated .js and .css files
    • generating a sha1 hash based on time (that's enough for me)
    • appending the hash to the files
    • updating the index.html with the new file names