Using Bower with Ruby Gem

I was browsing the source code of Trestle library written by Sam Pohlenz. I noticed that he uses bower to manage javascript libraries. The spec.files entry uses bower in the gemspec file. He was kind enough to explain how he did it in reply to my email. This article is based on his email.

The approach I take within Trestle is a little bit unorthodox. Some of the common ways to include asset-related dependencies in Rails is to either:

a) use a pre-packaged asset gem
b) use https://rails-assets.org/, or
c) include the assets beneath the vendor.

While option a) would be possible, it means that if the developer wants to use the same asset in their app, they must use the exact same version. Since Trestle uses some common dependencies such as jQuery and Bootstrap 3, I wanted to avoid this.

Option b) is also out since (as far as I know) it can’t be used for gem dependencies, only directly within an application's Gemfile.

Which leaves us with option c). Now rather than just download the assets directly into vendor/assets, we mange them using Bower so that they can be easily updated in future [side-note: I also use libraries.io to watch dependencies and notify me when they are updated]. By defining the dependencies in bower.json (and specifying a custom location for the bower_components directory in .bowerrc), we can then run bower update to keep everything up to date.

Another side-note: Bower is technically a bit out of date and people will say to use npm or yarn. However I had difficulties with both of these. From memory, the problems were related to

1) customizing the install location, and
2) locking the dependency versions.

The last piece of the puzzle is how we include the vendored assets into the asset pipeline. For each of the dependencies, I’ve created a glue file in either vendor/assets/stylesheets or vendor/assets/javascripts which includes the full ‘dist’ version of the vendored package, as well as setting any required variables or customizations (the font packages are a prime example of this).

The glue files then get

@imported 

or

// required

into Trestle’s main admin.scss/admin.js files.

References

Trestle Home Page
Trestle Repo


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.