rails asset pipeline

1 Min. Read
Dec 8, 2019

Rails Asset

Asset pipeline is a system for managing our static assets. Rails has all assets to be used in a project conventionally stored in assets folder inside app directory. This folder usually has all the javascript, images and stylesheets, also, fonts, audio, or video. The manifest or the main file for javascript ie application.js and for stylesheet ie application.css also lies here. These manifest files are the ones that are going to be sent to the browser. These files contains the specification of other files that are going to be combined and sent to the browser.

The reason for combining all the assets into one giant file is to save bandwidth by limiting the slow and resource intensive http requests that will otherwise be made for each individual file. It will also minify and compress the files alongside concatenation. The single file that all the assets are combined into is called a monolith file. Specification of other files inside the manifest files eg:

1
2
3
//= require dashboard
//= require_self
//= require_tree  etc

goes into the monolith file in the same order that they’re specified.

Asset pipeline also provides us with easy file paths that can be accessed using helper methods, by not having to remember the path of the file but just its name. It is also a pre processor that automatically converts scss, less, erb or coffeescript files to their corresponding counterparts.

The asset pipeline solves another issue of caching. The browser automatically caches the javascript files to improve page load performance. This will prevent it from loading a new version of the js oblivious to the changes made to the js files.

The following is the convention of storing assets into folders that is both understandable to the developer as well as facilitating to the asset pipeline’s functionality.

Precompilation

The asset pipeline provides a way for us to specify which files are compiled and in which order. By default, the manifest files are already included in the precompilation. Additional files can be included using either of the two methods.

1
2
  # in config/initializers/assets.rb
  Rails.application.config.assets.precompile += %w( dashboard.js dashboard.css signage.css signage.js)

the other option is to mention the file in manifest files to be compiled into a monolith file as:

1
2
3
4
5
6
7
#in application.css
 * require_tree .
 *= require ./utilities
 *= require ./common
 *= require font-awesome/css/font-awesome.min
 *= require ./vendor/jquery.dataTables
 *= require_self

Conclusion

Thus, using the asset pipeline and the functionality it offers can improve the usability, performance of our web app, as well as improving the conventional quality of our code. It makes it easier to code and serve static assets.