I’m writing a Javascript-rich application in a Ruby on Rails 3.1 project and using Handlebars for my JS templating framework. I’m trying to figure out a way to dynamically append the MD5 digest of an asset (generated during asset precompilation on production) to my tags inside of my Handlebars template. I’m hoping that there’s a hash with the asset path as the key and the MD5 digest as the value, but I haven’t been able to find one.
An ideal solution would be passing the hash from Ruby into Javascript and defining a Handlebars helper that would automatically append the MD5 digest to the “src” attribute of the asset.
Has anybody attempted to do something similar? There must be a way to use Javascript templates in Rails and also reap the benefits of asset fingerprinting.
As someone mentioned in the comments, appending a hash to the asset paths is a default part of the asset pipeline.
You can read more about fingerprinting in the asset pipeline here. Rails uses Sprockets to compile assets. The fingerprinting comes as part of Sprockets process.
You can use Sprockets’
find_assetmethod, passing in a logical path to your asset to get aSprockets::BundledAssetinstance. For exampleYou can call
digest_pathon this object to get it’sMD5sum appended to the asset.With this knowledge you can easily create a helper to return the
digest_pathfor any asset in your application, and call this helper from within your.js.erbfiles.