Rails breadcrumbs

As I was working on my new project, I was in need of a some breadcrumbs to implement on my site. Since I hate doing the same task over and over again, I looked for a ready to deploy plugin. After some googling, I quickly realised that a standard way of creating breadcrumbs is virtually impossible.

The way of creating your bread trail can depend on different situations and can change from project to project. I just think that this way of generating your bread trail I really neat, and would fit about 80% of most projects. The application controller code can even serve as a starting point for generating the trail dynamically.

Start and put the following in your application_controller.rb file:

protected 
def add_breadcrumb name, url = ''
  @breadcrumbs ||= [] 
  url = eval(url) if url =~ /_path|_url/
  @breadcrumbs << [name, url] 
end

def self.add_breadcrumb name, url, options = {} 
  before_filter options >do |controller| 
    controller.send(:add_breadcrumb, name, url) 
  end
end

Theses methods will be used in other controllers to build up the trail. Off course, every trail starts with the Home page. So it would be stupid to repeat that in every controller. The author of the blog post suggested to put

add_breadcrumb 'Home', '/'

in the top of your application controller, but that gave some problems for me. So what I did is, since I use the initialise method in my application method, is just to put the code right there.

So how do you continue to build up the trail you might think now? Just open an arbitrary controller and add something similar to the top:

add_breadcrumb 'Resource', '/resources'
add_breadcrumb 'List', '', :only => [:index, :destroy] 
add_breadcrumb 'Create a new resource', '', :only => [:new, :create] 
add_breadcrumb 'Edit a resource', '', :only => [:edit, :update] 

This way, all your crumb entries are grouped at the top of the controller. But if you need to customise, you can just add an entry in your action as well.

Now, you would like to view your breadcrumbs. Go to the right view (most likely you default layout page) and add the following code:

Source: http://szeryf.wordpress.com/2008/06/13/easy-and-flexible-breadcrumbs-for-rails/