Posts tagged ‘breadcrumbs’


Breadcrumbs in Rails

I’ve been working a little with Ruby on Rails recently.  One of the things I needed was a good module for handling navigational breadcrumbs.  I googled around a bit, but wasn’t able to find anything that fit my needs.  The closest to what I wanted was this example on stackoverflow.  It was a great starting point, but I ran into issues when I wanted to use nested controllers.  I wanted something a little more flexible.  Here’s my final solution.  I’m still a complete noob at rails, so feel free to point out any improvements you may have.

Features:

  • Splits up the URL and looks up the controllers for each section
  • Assumes you have a ‘name’ field on your data structure
  • Doesn’t link the last item since it should be the current pag
  • Works with nested controllers
  • Converts underscores to spaces and titleize’s the labels
  • Easy to modify to fit your own purposes

Code:

def get_bread_crumb(url)
    begin
        breadcrumb = ''
        so_far = '/'
        elements = url.split('/')
        for i in 1...elements.size
       
            so_far += elements[i] + '/'
           
            if elements[i] =~ /^\d+$/
                begin
                    breadcrumb += link_to_if(i != elements.size - 1, eval("#{elements[i - 1].singularize.camelize}.find(#{elements[i]}).name").gsub("_"," ").to_s, so_far)
                rescue
                    breadcrumb += elements[i]
                end
            else
                breadcrumb += link_to_if(i != elements.size - 1,elements[i].gsub("_"," ").titleize, so_far)
            end
           
            breadcrumb += " » " if i != elements.size - 1
        end
        breadcrumb
    rescue
        'Not available'
    end
end

Usage:

<%= get_bread_crumb(request.request_uri) %>

Which converts a URL like this:

/admin/posts/12/comments/8

to breadcrumbs like this:

Admin » Posts » Breadcrumbs in Rails » Comments » Great Post!

 37 comments