I was trying to understand how Rails’ asset pipeline works internally, so I had a quick code reading, annotating with bullet points each important step, then I thought about sharing it, may be helpful to others.
Note that this is for Rails 3.2.8, all links point to 3.2.8 tagged code. Sprockets integration with Rails 4.x is extracted to the sprockets-rails gem.
- Rails sets the default asset paths, setting
config.assets.pathsis the array that’s gonna be appended to the Sprockets environment load path.
- Rails sets the default accepted assets paths (rules in fact), setting
config.assets.precompileis the array that stores all rules that will be used to judge whether a asset is to be compiled or not.
- [ User can configure in
config/environments/<env>.rbmore rules to add to
- Rails instantiates and configures a Sprockets environment via railties using the configuration above (here)
- Rails will postpone configuring the Sprockets environment paths because other
gems could add more paths to the
config.assets.paths. Instead, it runs a
Sprockets::Bootstrapafter Rails is initialized (here)
Sprockets::Bootstrapwill then append
config.assets.pathsto the sprockets env paths (here)
- Now assets are configured, assets will be compiled when
rake assets:precompileis called, which will in turn instantiate a
Sprockets::StaticCompiler(provided by action_pack, not sprockets itself) instance and run (here)
- The compiler iterates over every single path inside the load paths,
recursively, and tests each entry against the rules defined in
config.assets.precompile, if any returns positively, it then compiles the asset and writes to the target directory (all that is here)