My First Rails Plugin – asset-format

For the first time ever today I wrote a rails plugin! I googled around first to make sure no-one had solved the particular problem I needed fixing but no-one seemed to have done, so I had no choice but to jump into the rails core…

The problem

In RubyonRails using the asset link tag such as:

<%= stylesheet_link_tag "screen", :media=>"screen, projection" %>

results in something like this on your HTML:

<link href="/stylesheets/screen.css?1234174480" media="screen, projection" rel="stylesheet" type="text/css" />

(view source on the Recycling Group Finder for the original). The number after the question mark (‘?1234174480’) is the asset ID. The idea behind the asset ID is that you can configure your web-server to set an Expires headers for your static assets far into the future causing browsers to cache the asset, but by changing the number (Rails does this automatically) you indicate to the browser that a file has changed and that the browser should re-fetch it. It works most of the time, but there are some mis-configured proxies out there (and possibly browsers too) that will cache the asset even when the asset id changes.

There’s a good description of the problem over on the sproutcore blog.

The Solution

This is where my plugin comes in, altering the asset URL with the asset ID in the URL, eg:

/stylesheets/screen.css?1234174480

becomes:

/stylesheets/1234174480/screen.css

Placing the asset ID in the URL, not the query causes proxies and browsers to see a different asset and so to fetch what it sees as a completely new asset. It will then cache the asset and if you change the asset ID the same thing will happen, no more over-cached assets!

Installing it

Easy, just:

$ cd rails_project_base_dir && script/plugin install git://github.com/wjessop/asset-format.git

start up your app and your asset URLs will be magically transformed! You will need a rewrite in your web-server config to rewrite the request back to the asset, so:

/stylesheets/1234174480/screen.css -> /stylesheets/screen.css

an you are all set!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s