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

折月煮酒 提交于 2019-11-29 01:45:49

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')
=> #<Sprockets::BundledAsset:0x3fe368ab8070 pathname="/Users/deefour/Sites/MyApp/app/assets/javascripts/application.js", mtime=2013-02-03 15:33:57 -0500, digest="ab07585c8c7b5329878b1c51ed68831e">

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.

This is an old question, but it seems that nowadays you can use assets_manifest:

Rails.application.assets_manifest.assets["application.css"] => "application-46ae33e78e504ff295219f41d63c79719d062e48dc0c07bd9b6f7bcad72c6636.css"

More discussion here: https://github.com/rails/sprockets-rails/issues/311

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!