Rails 3.1 introduced a new way to organize and process front-end assets called Asset Pipeline.
This was one of the biggest changes and brought me several issues associated because I didn't know how it really works.
After using it in some projects and reading about it, I learnt about it, and now is so much clearer :)
How does it work?
Basically, the Asset Pipeline (sprockets-rails rails module) has three main goals:
Collect, concatenate and minify assets into one file. (This reduce the number of request that a browser makes to render a web page)
Version assets, using a unique fingerprint in order to avoid cache issues. (So, you could invalidate the cache modifying this fingerprint)
For this, Rails uses sprockets gem(https://github.com/sstephenson/sprockets).
We can use it including it in our Gemfile with Bundler as follows:
gem 'sprockets', '~> 3.0'
You can change it using the following config option:
config.assets.css_compressor = :yui
config.assets.js_compressor = :uglify
Sprockets adds a hash at the end of the filename and that's what makes it unique.
An example could be: "application-6bcde4243667adf056c8a9951e8b1c9b.css"
Fingerprinting is enabled for production by default and is disabled for all other environments. It can be enabled or disabled by config.assets.digest option in your configuration.
How do we use it?
Well, asset pipeline is enabled by default in Rails 4.1 (last version of rails while I'm writing this post).
Rails automatically adds "sass-rails", "coffee-rails" and "uglifier" gems to your Gemfile. These are the gems used by rails-sprockets to serve your assets.
Every file you need has to be precompiled and in the public folder, so how do we do that?
The asset pipeline uses manifest files to know which files includes and the order between them.
That information is given by directives in the manifest file. Directives must begin with "//=" or “@import” for scss files.
//= require jquery //= require jquery_ujs //= require modernizr-2.5.3 //= require functions
@import “styles”; @import “main”; @import “font-awesome”;
(If you need more info about how to write manifest files and what are they for, you can read this post: http://www.foraker.com/rails-asset-pipeline-handling-of-css-and-js/)
Now, when we execute
RAILS_ENV=production rake assets:precompile task, it's going to create two files in public/assets:
Just as a comment, there's another two interesting tasks:
rake assets:clean and
The first one execute a cleaning of the assets files, keeping the last 3 precompiled assets, and the second one removes all temporal assets files.