02/21/06: JavaScript and CSS Versioning in Rails

To defeat browser caching for static files that actually do change once in a while, a common trick is to append a random number to the URL:
<link href="/css/mysite.css?9238238" rel="stylesheet" type="text/css">
If you use a truly random number (or the current time), it will reload every time. However, this is not exactly what you want; instead, you only want it to reload when the file has changed, and use the cached version when it hasn't. A good way to do this is to use the timestamp of the time the file was last modified.

Here's an easy way to do this in Ruby on Rails.

Use the standard Rails helper functions stylesheet_link_tag and javascript_include_tag (which reference static files inside the 'public' directory):

  <%= stylesheet_link_tag 'mysite' %>
  <%= javascript_include_tag "prototype" %>
Then add the following methods into your application_helper.rb:
 def javascript_path(js_file)

 def stylesheet_path(css_name)

 def versioned_path(path)
   if (path.include?("http://"))
     timestamp = File.mtime(File.join(RAILS_ROOT, "public",
     path + "?#{timestamp}"
That's it!

Comments made

Michael Kors has many styles to choose from, making this brand an ideal place to start looking for designer watches.
02/27/12 19:46:05
This kind of a cap can be a great gift for someone who likes to dress in a different way or who likes sporty clothes. Usually these caps do not cost a lot of money as well.
03/01/12 23:20:49
Men, women, young and old all alike will surely appreciate the gift whether it was given for any special occasion. They will make a very practical, durable and trendy gift that can be given.
03/01/12 23:21:10
The fact that he didn't don his T-Wolves jersey the second after the final buzzer sounded is no cause for concern. http://www.jeremylin17jerse...
03/20/12 23:13:41
Even though replicas in a good deal of situations are vastly inferior, craggy and are jagged-on-the-edges the fake Oakleys production current market has so advanced around the several years, that currently a ton of rigour and expertise goes into the manufacture of these splendid duplicate specimens.
Oakley Replacement Lenses
2012 Oakley Sunglasses
04/01/12 00:53:10

Add comment

Sorry, but due to blog comment spam, I have to ask you to create an account before you post a comment. Please log in (using the form on the top right of the page) or click here to create an account: Create an account!