Read more

Asset Pipeline Basics

Dominik Schöler
December 05, 2014Software engineer at makandra GmbH

The Rails asset pipeline improves delivery of application assets (javascripts, stylesheets, images, fonts). Here are some basic facts about its inner workings.

No magic

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Manifests are the handle on your assets:

app/assets/stylesheets/application.css # use via: stylesheet_link_tag 'application'

The asset pipeline only considers files you explicitly require within your manifest files. The most common directives used in manifests are require some/file and require_tree some/directory. Paths may be relative to the current directory or any of the asset search paths (see below).

Assets search path

By default, the following directories are considered, in the given order:

app/assets # for application stuff
lib/assets # for stuff that does not seem to fit into app/assets
vendor/assets # for external stuff

Grouping assets

Asset pipeline files may be grouped Show archive.org snapshot using an index file and then be used by simply requiring the directory they live in.

Index files are just sub-manifests. The need the corresponding file ending (e.g. .js for Javascript files), because "Sprockets assumes you are requiring a .js file when done from within a .js file".

Example

If there is an index file app/assets/stylesheets/blocks/index.css, you may simply require blocks in your application manifest. The index file is in charge of requiring the relevant files below its directory.

app
  assets
    stylesheets
    application.css
      blocks
        index.css
        foo.css.sass
        bar.css.sass

^

# app/assets/stylesheets/blocks/index.css
*= require foo
*= require bar

^

# app/assets/stylesheets/application.css
*= require blocks

Debugging

One step in debugging the asset pipeline is to check the precompilation results. You can do this locally using the following commands:

rake assets:precompile # precompiles to Rails.root/public/assets
rake assets:clobber # deletes the public/assets directory

After precompilation, you can check the generated files in public/assets for correct URLs in CSS files etc.

Posted by Dominik Schöler to makandra dev (2014-12-05 12:21)