Bower With Rails

Today, after a long time without posting I will show you how to integrate bower in a Rails application. Many times I was a bit frustrated when I found a nice lib I want to include in a project but when I want to find the associated gem, sometimes the lib is not up to date inside and I have to wait for the new version of the gem… Another solution is to download the version of the lib you want and put it in the vendor directory but in that case it can be really boring to maintain…

Now there is a solution for that thanks to Bower.

First step, you have to add the gem bower-rails in your Gemfile then the classic bundle and finish with rails g bower_rails:initialize.

Now you can have a look on your new file in your initializers directory.

config/initializers/bower_rails.rb
1
2
3
4
asset 'angular'
asset 'angular-resource'
asset 'angular-route'
asset 'requirejs'

This is an exemple with angular and requirejs loaded. Then you just need to run the command rake bower:install and your bower.json file will be created/updated and your libs downloaded in your vendor directory. Of course you can set a specific version, change the destination directory etc… I’m sure you will have a look on the doc if you want more details.

Now because the vendor path is in the assets path of rails you can simply include your files in your application.js file (also your stylesheets).

application.js
1
2
3
4
5
//= require_self
//= require angular
//= require angular-resource
//= require angular-route
//= require requirejs

That’s it ! So now you can remove all the gems you have for different lib you use like your twitter-bootstrap, zurb-foundation, backbone, angular… and just load everything using bower. Maybe the next step will be to use Grunt instead of sprockets for my asset pipeline.

Comments

Copyright © 2014 - Anthony Estebe -