iprog.com

Disabling Rails asset timestamps

One of the common questions in Rails land is how to disable the funny numbers at the end of images and CSS stylesheets. Let’s explore what exactly those numbers are, why they’re sometimes helpful, and how to turn them off when they’re not.

Those numbers are timestamps — the number of seconds since January 1, 1970. The time is the last time the image or stylesheet was last modified.

So if the time is June 26, 2009 at 02:39:24, then the timestamp would be 1245983964.

Great! Now, why do we care?

Rails appends these timestamps to cause web browsers to think the files are unique. This causes a browser to not use its cache and to reload the file. That is, even those these reference the same file, the browser thinks they are different.

1/stylesheets/styles.css?1245981180
2/stylesheets/styles.css?1245983964

Let’s backtrack just a little. Web browsers, in an effort to show you a page faster, will keep a copy of recently loaded files either in memory or on your hard disk. If it is just told to load 1/stylesheets/styles.css and you change the CSS file, the web browser might use the old copy in the cache rather than load the new version of the file.

However, by appending these timestamps on the end, when the file changes, the browser will also think it’s a different file and will always load the new copy.

So it’s really a useful feature most of the time.

Sometimes it can get in the way (or you may just think it’s ugly and aren’t concerned about browser caches. For those instances, you can turn it off.

1ENV['RAILS_ASSET_ID'] = ''

You should add a new file in your 1config/initializers/ directory to put that in. Let’s call it no_timestamps.rb. So, in 1config/initializers/no_timestamps.rb, just add the one line above. Then, restart your Rails server.

That’s it! No more appended timestamps.

Updated 11/12/2009: As noted in the comments, I had incorrectly suggested using cache_asset_timestamps=false. Corrected the above to show the proper way to do this.

tags: rails

by Dave

That’s not correct, actually. Setting cache_asset_timestamps to false does exactly what it says: It will calculate and append the last modified time of the file but it won’t cache it so that the next request made Rails will grab the mtime again (rather than reading it from the cache).

To disable the timestamps, in your no_timestamps.rb initializer, just put: ENV[‘RAILS_ASSET_ID’] = ’’

by tm

Dave, thanks for the correction. Not sure how I screwed that up, but I did. I’ve updated the post to reflect the proper way to do this.

—t