asset_path(带指纹)来自数据库?

asset_path (with fingerprint) from database?

我开发了一个带练习的 rails 应用程序(适用于有数学学习困难的孩子)。习题的交互部分写在javascript中。我将每个练习存储在数据库中。 javascript 包含

<%= asset_path('to_images') %>

我可以将脚本读入控制器并将内容写入部分,但我认为将脚本捕获到变量中会更好,例如:

@animation = exercise.animation

任何包含 <%= asset_path(...) %> 的代码都将被替换为资产的正确指纹路由。

这是 exercise.animation 中的代码片段示例:

$("#hundred_square td").css({
    backgroundImage: 'url(<%= asset_path("exercises/shapes/circles/circle_open_black_48.png") %>)',
    backgroundSize: "2vw",
    backgroundRepeat: "no-repeat",
    backgroundPosition: "center"
});

我已经试过了

class Exercise < ActiveRecord::Base
include ActionView::Helpers::AssetUrlHelper

self.animation.gsub(/\<\%\=\s*asset_path\((.+)\)\s*\%\>/) do |match|
  address = 
  puts "#{address}"
       =>  "exercises/shapes/circles/circle_open_black_48.png"
  puts "#{asset_path(address)}"
       =>  /"exercises/shapes/circles/circle_open_black_48.png"
  puts "#{ActionController::Base.helpers.asset_path(address)}"
       =>  /"exercises/shapes/circles/circle_open_black_48.png"
end

没有产生我需要的结果。 感谢您的建议!

获取 MD5 指纹值的一种方法是使用 Sprockets 的 find_asset 方法,传入资产的逻辑路径以获取 Sprockets::BundledAsset 实例。例如

[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 总和。

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

有了这些知识,您可以为应用程序中的任何资产创建 return digest_path 的助手,从 .js.erb 文件或模型中调用此助手。

this answer for more details on this approach.