How can I determine the MD5 digest of a given asset in the Rails asset pipeline?

后端 未结 2 360
太阳男子
太阳男子 2020-12-15 23:00

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

2条回答
  •  一生所求
    2020-12-15 23:25

    As someone mentioned in the comments, appending a hash to the asset paths is a default part of the asset pipeline.

    In production, Rails inserts an MD5 fingerprint into each filename so that the file is cached by the web browser

    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_asset method, passing in a logical path to your asset to get a Sprockets::BundledAsset instance. For example

    [1] pry(main)> Rails.application.assets.find_asset('application.js')
    => #
    

    You can call digest_path on this object to get it's MD5 sum appended to the asset.

    [1] pry(main)> Rails.application.assets.find_asset('application.js').digest_path
    => "application-ab07585c8c7b5329878b1c51ed68831e.js"
    

    With this knowledge you can easily create a helper to return the digest_path for any asset in your application, and call this helper from within your .js.erb files.

提交回复
热议问题