Even though the asset pipeline was announced a few months ago and has been available in Rails 3.1 for a while now, it’s taken me some time to getting to complete understanding what it’s all about. I’ve tried to condense what I’ve learned here in a post that you can hopefully digest in 5 minutes or so.
As David Heinemeier Hansson said at Railsconf 2011, the asset pipeline has one main goal, that is to make it easy to treat assets such as js code and css as first class citizens in your Rails app. Practically it does so using 3 things, asset directories, manifest files and engines.
In Rails 3.1 your assets can live in one of three (default) directories
- app/assets for assets that are closely coupled with your application
- lib/assets are for your own custom libraries that can be shared across applications
- vendor/assets are for third party assets used by your application
Once in these directories, the pipeline will be aware of your assets, and can now do a number of helpful things. First off, Rails will help you organise and manage dependencies between your assets, using manifest files. Next, it can run a number of preprocessors using engines, letting you use things like Coffeescript and Sass. Finally it will give you all of the minification, file concatenation and caching fingerprint goodness for your production environment.
// ... //= require jquery //= require jquery_ujs //= require_tree .
/* ... *= require_self *= require_tree .
These manifest files reference and include other assets that they depend on. require_directory and require_tree lets you require whole directories and their children, require_self also includes any js or css in the manifest file itself.
These are run from right to left, for example styles.css.scss.erb will first run the file through erb and then Sass.
Yep, that’s basically the least amount I can say about the asset pipeline without being useless. Of course I have left out a ton of stuff, but luckily there are some excellent resources out there to fill you in on the details:
I’m very honored that Michael Hartl based the structure of his section on the asset pipeline on this post in his most excellent Ruby on Rails tutorial. I would highly recommend this tutorial as the best way to learn Rails.