如何确定 Rails 资产管道中给定资产的 MD5 摘要? [英] How can I determine the MD5 digest of a given asset in the Rails asset pipeline?

查看:37
本文介绍了如何确定 Rails 资产管道中给定资产的 MD5 摘要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Ruby on Rails 3.1 项目中编写一个富含 Javascript 的应用程序,并在我的 JS 模板框架中使用 Handlebars.我正在尝试找出一种方法,将资产的 MD5 摘要(在生产的资产预编译期间生成)动态附加到我的 Handlebars 模板内的标签中.我希望有一个以资产路径为键、以 MD5 摘要为值的散列,但我一直找不到.

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.

一个理想的解决方案是将哈希值从 Ruby 传递到 Javascript 并定义一个 Handlebars 助手,它会自动将 MD5 摘要附加到资产的src"属性.

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.

有没有人尝试过做类似的事情?必须有一种方法可以在 Rails 中使用 Javascript 模板并获得资产指纹识别的好处.

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.

在生产中,Rails 在每个文件名中插入一个 MD5 指纹,以便网络浏览器缓存该文件

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

您可以阅读有关资产管道中指纹识别的更多信息此处.Rails 使用 Sprockets 来编译资产.指纹识别是 Sprockets 流程的一部分.

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.

您可以使用 Sprockets 的 find_asset 方法,将逻辑路径传递到您的资产以获取 Sprockets::BundledAsset 实例.例如

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">

您可以在此对象上调用 digest_path 以获取附加到资产的 MD5 总和.

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"

有了这些知识,您可以轻松地创建一个帮助程序来返回应用程序中任何资产的 digest_path,并从您的 .js.erb 文件中调用此帮助程序.

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.

这篇关于如何确定 Rails 资产管道中给定资产的 MD5 摘要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆