Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate asset IDs in Rails 3 to control cache?

In Rails, when serving static files, you get an asset ID that's appended to the URL, e.g.,

<script src="/javascripts/application.js?1300371955" ...
<link href="/stylesheets/custom.css?1299690788" ...

This way, the URL of a static file is changed if the file’s timestamp is changed and browsers automatically request the new file.

I saw that by using the helper methods for including static assets --- stylesheet_link_tag, javascript_include_tag and image_tag --- Rails automatically adds timestamps to all references to those files.

How can I implement something similar for other assets that don't have such helper methods
e.g., .swf files?

(Does this "strategy" to force the re-download have a name; if so, what is it called?)

like image 775
Marius Butuc Avatar asked Nov 26 '25 21:11

Marius Butuc


1 Answers

The Rails method that appends the timestamp to assets is called rails_asset_id, and is defined in ActionView::Helpers::AssetTagHelper. Though it is a private method, it can be accessed in a helper to generate one for your custom tags like so:

def swf_param_tag(path)
  asset_id = rails_asset_id(path)
  "<param name='movie' value='#{path}?#{asset_id}'/>"
end

It needs you to pass in the path, because it then calls File.mtime(path).to_i.to_s on it to get the last modified time on it.

There is further explanation about what the asset tag buys you here: http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html

like image 146
Unixmonkey Avatar answered Nov 28 '25 10:11

Unixmonkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!