Posted over 4 years ago. Visible to the public.

Managing vendor libraries with the Rails asset pipeline

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:

Copy
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:

Copy
# 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:

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

Your app/assets/stylesheets/application.css:

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

And you'll embed icons with

Copy
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.

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Dominik Schöler
Last edit:
11 months ago
by Emanuel De
Keywords:
frontend, javascript, js, css, asset, libs
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Dominik Schöler to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more