Book Image

Bootstrap for Rails

By : Syed F Rahman
Book Image

Bootstrap for Rails

By: Syed F Rahman

Overview of this book

Table of Contents (18 chapters)
Bootstrap for Rails
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Adding Bootstrap-sass to a Rails application


In the Installing Bootstrap in the Rails project, section in chapter 2, Introducing Bootstrap 3 we saw how to include Bootstrap into our Rails application through three different ways:

  • The CDN method

  • Bootstrap-sass gem

  • By downloading Bootstrap files

To quicken things up, we had opted for the CDN method. Well, in this chapter, we are going to use Bootstrap through Bootstrap-sass gem. This will enable us to completely customize the Bootstrap's default styles. So, let's proceed and install Bootstrap-sass gem in our application:

  1. Go to the application folder and edit the file Gemfile using a text editor. Add the following two lines of code at the end of this file:

    gem 'bootstrap-sass', '~> 3.3.1'
    gem 'autoprefixer-rails'
  2. The above two lines will install bootstrap-sass and autoprefixer-rails gems into your application. The autoprefixer-rails is needed to automatically append browser vendor prefixes in the CSS stylesheets.

  3. Let's bundle the application, so that the above gems are actually downloaded and installed in our application.

    bundle install
    
  4. Once the execution of the above command is complete, navigate to the app | assets | stylesheets folder. Rename the application.css file to the application.css.scss file. Next, remove the imported CDN link from the file, which was included by us earlier.

  5. Now, we need to include Bootstrap files that are downloaded through gem inside the application.css.scss file. To do that, include the following 2 lines:

    @import "bootstrap-sprockets";
    @import "bootstrap";

    The bootstrap-sprockets value is needed to correctly link the font files with the Bootstrap's CSS files.

It's time to link the Bootstrap's JavaScript files using the recently gem:

  1. First, we need to remove the hardcoded Bootstrap's JavaScript CDN link from the application.html.erb file, present in the layouts folder by navigating to app | views | layouts folder. Remove the following line from this file:

    <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
  2. Next, go to the JavaScript folder by navigating to app | assets | javascript folder and edit the application.js file. Add the following line immediately after the jQuery line:

    //= require bootstrap-sprockets
  3. Finally, we are done. If you reopen your application in the browser, you can see that everything is working, just like before.