Jakub Chodounský

Managing front-end libraries with Bower in Rails

Recently, I’ve been playing with Ruby on Rails and I had to integrate bower—a package manager for front end libraries. The reason for this was that I needed to add Pure library to one of my projects and I didn’t want to maintain it by hand.

For this purpose, I used a gem called bower-rails which is very promising, so let’s take a look at the installation process. If you are new to rails as I am, it’s not that easy as you might think.

Firstly, you need to install the gem into your projects. The best way to install a gem is to modify your Gemfile and add the line

gem "bower-rails", "~> 0.7.1"

and run the following command to install new dependency.

bundle install

The next step is adding a bower configuration file to the project. Create a file called bower.json in the root of your rails application with the following content.

{
  "name": "bower-rails generated vendor assets",
  "dependencies": {
    "pure": "0.4.2"
  }
}

The name isn’t important, but the dependencies part is. It lists all the libraries you want to add to your project, so I added “pure” framework there, but you can add jquery or whatever comes to your mind.

After that, you run the bower within the rails by invoking this command.

rake bower:install

And it should install all your bower dependencies to the folder vendor/assets/bower_components.

You need to add the path vendor/assets/bower_components to your asset pipeline. The asset pipeline is something that is processing your stylesheet and javascript files and link them to your HTML. And this could be achieved by adding the following line into config\application.rb.

// ...
config.assets.paths << Rails.root.join('vendor', 'assets', 'bower_components')
// ...

When you are ready, restart your application by killing the rails server. I wasn’t aware of that and spent couple hours investigating what was wrong. Don’t do this, it’s not fun.

Finally, you are ready to add the component to your project by linking in an application.css or application.js file depending on the type you added. I am linking a stylesheet so I have to modify the app\assets\stylesheets\application.css and add a path to pure-min.css file like this:

 * ...
 *= require pure/pure-min
 *= require_self
 *= require_tree .
 */

That’s it. We just integrated bower into rails project to manage our front-end library dependencies.

One last thing, there is another way of doing this without using bower directly. The project rails-assets uses only gem package manager to maintain bower dependencies. Check their site, it looks much easier than the solution we just did.