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 si开发者_StackOverflow中文版milar 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?)
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
@Unixmonkey: your solution works very well.
As an alternative there's also the swf_fu plugin:
treat your Adobe Flash swf files like any other asset (images, javascripts, etc...) and embed them using SWFObject 2.2
that has asset tagging built-in.
精彩评论