Managing vendor libraries with the Rails asset pipeline

Updated . Posted . Visible to the public.

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

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.

Dominik Schöler
Last edit
Klaus Weidinger
Keywords
frontend, javascript, js, css, asset, libs, asset-libs, vendor/asset-libs
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2014-12-08 10:06)