How do I retrieve the Rails cache-busting timestamp?
I'm quite new to Rails, so please .. be gentle. :)
There's apparently a cache-busting timestamp that g开发者_运维百科ets appended as a querystring to JavaScript and CSS includes in Rails. How can I obtain that value programmatically? (I'd like to be able to use it for other purposes.)
It's the last modified timestamp of the file in question. Rails calculates it in ActionView
's asset_tag_helper.rb
as follows, but the important part is File.mtime(path).to_i
# Use the RAILS_ASSET_ID environment variable or the source's
# modification time as its cache-busting asset id.
def rails_asset_id(source)
if asset_id = ENV["RAILS_ASSET_ID"]
asset_id
else
if @@cache_asset_timestamps && (asset_id = @@asset_timestamps_cache[source])
asset_id
else
path = File.join(ASSETS_DIR, source)
asset_id = File.exist?(path) ? File.mtime(path).to_i.to_s : ''
if @@cache_asset_timestamps
@@asset_timestamps_cache_guard.synchronize do
@@asset_timestamps_cache[source] = asset_id
end
end
asset_id
end
end
end
There are multiple ways to do that. If you deploy with Capistrano, one thing you can do is to set ENV['RAILS_ASSET_ID']
of the version number contained in REVISION.
As I posted, it's easy if youj deploy with Capistrano as the REVISION file contains a unique hash id, but you could also create your own version id and assign it to RAILS_ASSET_ID.
精彩评论