Wrap breadcrumbs_on_rails for Bootstrap 3

Using the breadcrumbs_on_rails gem was easy enough for my current Rails 4 / Bootstrap 3 project. What took a little more work was fitting them into the site’s look and then refactoring some iffy code that got introduced into the controllers.

To turn these:
breadcrumbs-before
Into these:
breadcrumbs-after

(In the controller vs. views debate for breadcrumbs, while I can see how conceptual they belong in the views, in practice they seem easier to maintain in the controllers.)

Styling Each Crumb

The design requirement was to use the Bootstrap classes to turn the links into buttons with icons at the top levels. This meant a custom builder. The following code placed in lib/bootstrap_breadcrumbs_builder.rb:

This builder is based on @equivalent’s gist. There is also an interesting discussion in the comments of this gist as well. I doubt very much if this is the end of styling the breadcrumbs but this basic builder is a nice starting point.

The render call then becomes:

Once you have the Bootstrap classes, the icons can simply be added to the breadcrumb title:

However – yuck!

Refactor the HTML out of the controllers

Time to move the titles with their HTML to a locale file and add a wrapper method for add_breadcrumbs.

First, the wrapper method:

With this wrapper, you can added breadcumbs with the path or an ordered array of paths. The title will be pulled from a locale file (which is where it belongs anyway).

Since this method needs to be callable by any controller, the traditional Rails way would be to put the method in the applications_controller.rb. And that will work.

However, since I loath to add more bloat to the applications controller and my version of Rails is set-up for them, I created a concern module. The method goes in a file called app/controllers/concerns/application/add_crumb.rb inside module Application::AddCrumb. This way the only line needed in applications_controller.rb is include Application::AddCrumb

The locale file would look something like this:

The result is calls in the controller like:

Much better.