now available

now available
Want fresh tech tips in your inbox?

Very Simple Breadcrumb Navigation in Rails with Before_filter


This may not be the ideal solution. This just manages request.referers in a session variable, then looping over each unique path prints a link to the screen. It's more of a "history" than a hierarchy for resources in an application. It is however, pretty straight forward to implement.

First create a before_filter in your application controller.Call it on every action. In the definition we'll parse the request.referer variable with the URI::parse method so that we're only dealing with the relative, not absolute, resource. We'll make sure that we're only storing unique paths and if the user arrives at an index action, we set the session[:breadcrumbs] variable to nil. This indicates that they are at the top level.



before_filter :setup_breadcrumb_navigation protected def setup_breadcrumb_navigation if params[:action] == "index" session[:breadcrumbs] = nil else url = URI::parse request.referer if session[:breadcrumbs].nil? session[:breadcrumbs] = url.path.strip else session[:breadcrumbs] = session[:breadcrumbs] + ", "+url.path if session[:breadcrumb] end session[:breadcrumbs] = session[:breadcrumbs].split(", ").uniq.join(",") end end end

The helper function just splits apart the string stored in the session[:breadcrumbs] variable, looping over the relative paths. We link to them, but first replace the ugly "/" and preface the display with some form of delimiter. I chose to use the "::" which looks nice to me.


def breadcrumbs content_tag :span, :id=>"breadcrumbs" do if not session[:breadcrumbs].blank? session[:breadcrumbs].split(",").uniq.map{ |breadcrumb| link_to(" :: "+breadcrumb.to_s.gsub("/"," ")+"",breadcrumb) } end end end

This is definitely a hack. You won't necessarily find a hierarchical relationship between links in the breadcrumb navigation. However, it will display the users history letting them quickly access a resource they just visited a page or two before. It's perhaps 80% of the functionality for only 5% of the work.

Oh yeah, putting this in a view


<%= breadcrumbs %>

Tagged w/ #before_filter #breadcrumbs #hacks #navigation #referers #restful #sessionsruby on rails

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app