antelio
7/30/2015 - 12:31 AM

Rails4 + Bower + Bootstrap set-up

Rails4 + Bower + Bootstrap set-up

This document is outdated. You should read David Bryant Copeland's excellent online book: http://angular-rails.com/crud_recipe.html


I think it's better to install javascript/css libraries using Bower rather than gem which is Ruby packager.

  1. Install Rails 4 and create a new project.

  2. Install bower(Note you need to install node first.) sudo npm install -g bower

  3. Create .bowerrc file in your project directory. Bower will install packages in the specified directory. { "directory": "vendor/assets/bower_components" }

  4. Now you can install packages using Bower. e.g. bower install bootstrap

  5. Rather than installing packages manually, you should create a Bower manifest file(bower.json) in the project directory. e.g. my manifest to install bootstrap and angular. { "name": "cakeroster", "version": "1.0.0", "dependencies": { "bootstrap":"~3.0.0", "angular": "~1.0.7", "angular-cookies": "~1.0.7", "angular-loader": "~1.0.7", "angular-resource": "~1.0.7", "angular-sanitize": "~1.0.7" }, "ignore": [ "*/.", "node_modules", "bower_components", "test", "tests" ] }

  6. Install all the packages using bower.json bower install

  7. Install LESS compiler by adding two gems in Gemfile gem "therubyracer" gem "less-rails"

bundle install

  1. Update application.css so that Rails asset pipeline picks up bootstrap /* *= require_self *= require_tree . */

  2. Create bootstrap.css.less in app/assets/stylesheets directory @import "bootstrap/less/bootstrap"; @import "bootstrap/less/responsive";

Because 'require_tree .' is specified in application.css, the asset pipeline will pick up 'bootstrap.css.less'.

This setup allows us to load LESS files from Bootstrap package directory. However, Bootstrap package also has static css files in its doc directory. If you specify 'require bootstrap' in application.css, Sprocket will read bower.json file in the bootstrap pacakge directory which points static css files in the doc directory. But I think these css files are meant to be used by Bootstrap document html files. So I prefer to use the LESS files.

  1. In order to load javascript files for Bootstrap, specify Bootstrap package in application.js file. //= require jquery //= require jquery_ujs //= require turbolinks //= require bootstrap

  2. Create bootstrap.js file in verndor/assets/bower_components directory. //= require_directory ./bootstrap/js

With the same reason I explained above, I rather load js files from proper place.

  1. A few gotchas
  • Sprocket supports Bower packages. If you specify package name with require directive, it will load appropriate files using bower.rc of the package.
  • require_tree and require_directory directives only loads from the directory relative to the manifest file(i.e. application.css or application.js). In order to work around this issue, create "nested manifest file" as I suggested step 10 and 11.