Lesson Monday

By default, Rails enables a feature called the asset pipeline for managing an application's CSS, image and JavaScript assets. In this lesson, we'll give an overview of the asset pipeline and add Bootstrap to our application for styling. We'll also briefly discuss Sass and CoffeeScript, which are both preferred in the Rails community for handling CSS and JavaScript. Don't worry — plain old JS and CSS work as well. You are not expected to learn either Sass or CoffeeScript, but it's good to be aware of both.

Asset Pipeline Features


The main features of the asset pipeline are:

  • Concatenation: All JS files are concatenated into a single .js file and all CSS files are concatenated into a single .css file. This allows the browser to make fewer requests so our pages load more quickly.

  • Asset Minification: CSS and JavaScript files are minified to allow for maximum speed in processing.

  • Ability to code assets using Sass for CSS and CoffeeScript for JavaScript.

Sass and Bootstrap

Sass (Syntactically Awesome Stylesheets) is a CSS language. It allows us to enhance our CSS writing by offering features that are not available in straight CSS such as variables, inheritance, mixins, nesting and arguments. We write our code in Sass and then the Sass is converted into a standard CSS file so our application can use it.

In class, we will use Sass to add Bootstrap to our applications with the gem bootstrap-sass. Follow the installation instructions for Ruby on Rails to get Bootstrap in place.

Images

We should store images in the app/assets/images directory. We can then use the image_tag helper to call them like this:

<%= image_tag "rails.png" %>

CoffeeScript


CoffeeScript is another supported language in the Rails asset pipeline. It allows us to write streamlined code that compiles into JavaScript. Check out the CoffeeScript site for an overview. We will not be reviewing code for CoffeeScript in this class but you are welcome to explore. The goal of CoffeeScript is to make JavaScript cleaner and easier to read.

For more information on the asset pipeline, visit the RailsGuides documentation especially these sections:

Lesson 21 of 34
Last updated August 7, 2022