I thought I might find a short snippet, plugin, gem, whatever, somewhere on the web that would translate my request URI into a simple breadcrumb. Unfortunately, I didn’t find anything within the first several pages of the several different Google searches I performed, so I thought to myself, “How hard could it be?”. Not hard at all actually. (Still harder than copying someone else’s code though.. hehehehe.)

So, here it goes. My requirements were:

  1. Breadcrumb nodes should be listed in an unordered list
  2. The first node in the trail should always be the "home" link.
  3. The last node in the series should not be clickable - since we're already on that page.
  4. In the case of an edit, show, or any other action where the id param was stuck onto the end of the URL, I didn't want that id as part of my breadcrumb trail, thus making the action name the last node in the list - and unclickable per #3 above.
  5. Any other query string params (e.g. http://url/?variable=value) obviously should not wreak havoc on my breadcrumbs either.
  6. Translate all underscores "_" into spaces.

Now, I realize its pretty crude at this point. It appears to be working for what I need it for. Hopefully someone else finds this and can make it better in some way.

  <li><a href="/">home</a></li>        
s = ""
url = request.path.split('?')  #remove extra query string parameters
levels = url[0].split('/') #break up url into different levels
levels.each_with_index do |level, index|
  unless level.blank?
    if index == levels.size-1 || 
       (level == levels[levels.size-2] && levels[levels.size-1].to_i > 0)
      s += "<li>#{level.gsub(/_/, ' ')}</li>\n" unless level.to_i > 0
        link = "/"
        i = 1
        while i <= index
          link += "#{levels[i]}/"
        s += "<li><a href=\"#{link}\">#{level.gsub(/_/, ' ')}</a></li>\n"

This was stuck in a partial and rendered from within my application layout. Not sure how this would handle performance wise, but right now its doing the job!

Its still a bit perplexing that nothing of this sort has already been written elsewhere. There’s probably a more elegant solution than the one I’ve came up with.