asset_path (with fingerprint) from database?

asset-pipeline, ruby, ruby-on-rails, ruby-on-rails-4

Solution

One way to fetch the MD5 fingerprint value is to 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 create a helper to return the `digest_path` for any asset in your application, call this helper from within your `.js.erb` files or from within your model.

See this answer for more details on this approach.

Problem

I develop a rails app with exercises (for kids with learning difficulties in math). The interactive part of the exercises is written in javascript. I store each exercise in a database. The javascript contains ``` <%= asset_path('to_images') %> ``` I can read the scripts into the controller and write the content to a partial, but I think it would be better to capture the scripts in a variable, like: ``` @animation = exercise.animation ``` where any code containing <%= asset_path(...) %> would be replaced with the correct fingerprinted route to the asset. Here is an example of a code snippet in 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" }); ``` I have already tried to ``` class Exercise < ActiveRecord::Base include ActionView::Helpers::AssetUrlHelper ``` and ``` self.animation.gsub(/\<\%\=\s*asset_path\((.+)\)\s*\%\>/) do |match| address = $1 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 ``` do not produce the result I need. Thanks for your suggestions!

Original source

Related problems