DBTV Dev Blog

Talk is cheap. Show me the code.

Understanding the Asset Pipeline in Rails 3.1

Asset Pipeline

The asset pipeline provides a framework to compress JavaScript and CSS assets.

It also adds the ability to write assets in other languages like CoffeeScript, Sass and ERB.

What The Asset Pipeline Does

Concatenate assets

By combining all your css and js assets into single files you can reduce load time by decreasing the number of requests a browser needs to make.

Minification and Compression

In addition to combining your assets, the pipeline will remove all the extra line breaks and whitespace. The helps in load time and also prevents others from stealing your scripts.

Fingerprinting

To prevent old cached versions of images and static files being loaded, the asset pipeline adds a serial number to the end of files. For example, global.css would be transformed to something like:

1
global-908e25f4bf641868d8683022a5b62f54.css

How To Use The Asset Pipeline

Files to include in the pipeline can be placed in three places: app/assets, lib/assets or vendor/assets. When calling these assets in your views, you no longer have to worry about the full file path – you can simply call them by the file name. For example:

1
<%= image_tag "rails.png" %>

You can also include (or remove) specific files or directories by using manifest files. For example, a new Rails application includes a default app/assets/javascripts/application.js file which contains the following lines:

1
2
3
4
// ...
//= require jquery
//= require jquery_ujs
//= require_tree .

To learn more about the asset pipeline visit the Rails Docs or watch the Rails Cast.