Read more

Managing vendor libraries with the Rails asset pipeline

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

The benefit of the Rails asset pipeline is that it compiles your stylesheets and javascripts to a single file, respectively. However, the consequences are startling if you don't understand them. Among others, the raw asset pipeline requires you to have all your asset libraries in the same folder, which quickly becomes confusing as your set of assets grows. To overcome this, we have two different solutions.

Custom solution

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

We are using a custom workaround to keep library files apart in their own directories. To avoid breaking stylesheet concatenation, we gave every library its own "root" folder. First, add this line to your config/initializers/assets.rb:

Rails.application.config.assets.paths += Dir["#{Rails.root}/vendor/asset-libs/*"].sort_by { |dir| -dir.size }

This will tell Rails about the custom asset library location. The weird sorting is necessary, since the pipeline does some unfortunate prefix detection, and would detect jquery-ui/jqueryui.js to live in the jquery folder. Putting longer folders first fixes this.

We organize stuff like this:

# jquery goes here
vendor/asset-libs/jquery/jquery.1.7.2.min.js

# jquery-ui goes here
vendor/asset-libs/jquery-ui/jquery-ui-1.8.21.custom.min.js
vendor/asset-libs/jquery-ui/jquery-ui-1.8.21.custom.css
vendor/asset-libs/jquery-ui/images/....

# icon set goes here
vendor/asset-libs/fugue/icons/....

Your app/assets/javascripts/application.js:

...
//= require jquery.1.7.2.min
//= require jquery-ui-1.8.21.custom.min
...

Your app/assets/stylesheets/application.css:

...
 *= require jquery-ui-1.8.21.custom
...

And you'll embed icons with

background-image: image-url(icons/abacus.png)

Fixing font paths

When you manually manage a library that brings its own fonts, you might need to update URLs in the library's files. I.e., when the library's CSS expects font files at the wrong location, you can rename the requiring CSS file to .css.scss, turn calls to url into font-url (requires SASS) and pass a valid path to that font.

To reference a file in /vendor/asset-libs/<library>/fonts/<font file>, you need to write font-url('fonts/<font-file>').

Caveat

Since all stylesheets will end up in the same folder, you will have a problem if your assets and any library's have identical names.

Posted by Dominik Schöler to makandra dev (2014-12-08 11:06)