Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the format of Rails asset_tag URLs?

Background

I'm currently working on a Rails 3 project that I intend to use with Amazon CloudFront with a custom origin pointing back to my actual web server. This means that my web server will tell the browser to retrieve static assets from CloudFront, if CloudFront has the asset cached it will return it, if it does not it will retrieve it using the same path from my web server and then cache it for future requests.

Problem

Amazon CloudFront drops and ignores query string parameters when determining whether it should bust it's own cache to re-download the asset from it's origin. This obviously poses a problem with the way Rails generates URLs with the RAILS_ASSET_ID which is to do: /assets/path/to/asset.ext?RAILS_ASSET_ID. With the default asset URLs CloudFront will hold onto stale assets for up to 24 hours.

Solution?

What I'm hoping to do is somehow override the way Rails 3 generates asset tags so that I can generate URLs like /assets/RAILS_ASSET_ID/path/to/asset.ext. I already have a solution for how to make the web server respond to those URLs, I just need to figure out how to make Rails generate the URL.

Notes

  1. My RAILS_ASSET_ID will be a sub-string of my latest git commit hash. Setting this will be handled by capistrano during the deployment process. I am OK with busting all asset caches on each deployment, I don't need asset-specific IDs
  2. I have already attempted to override ActionView::Helpers::AssetTagHelper.rewrite_asset_path but it didn't seem to work and from what I read this is a private method that should not be relied upon.
  3. Thank you in advance!
like image 343
THREE Avatar asked Dec 22 '10 14:12

THREE


1 Answers

"Set ActionController::Base.config.asset_path to a proc that takes the unmodified asset path and returns the path needed for your asset caching to work."

That's from the AssetTagHelper documentation.

like image 92
John Avatar answered Sep 23 '22 17:09

John