Skip to content

Instantly share code, notes, and snippets.

@jackdesert
Forked from sprsquish/gist:445553
Last active December 14, 2015 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackdesert/5117696 to your computer and use it in GitHub Desktop.
Save jackdesert/5117696 to your computer and use it in GitHub Desktop.
A helper method that creates a breadcrumb based on your current url
module Admin::BreadcrumbHelper
# BREADCRUMB HELPER
#
# This module is useful anywhere you want to create a basic bread crumb
# I generally use it
# INSTALLATION for ADMIN DASHBOARD
# 1. Save this file to app/helpers/admin/breadcrumb_helper
#
# INSTALLATION for NORMAL USE
# 1. Save this file to app/helpers/breadcrumb_helper
# 2. Change the module definition from
# module Admin::BreadcrumbHelper
# to simply
# module BreadcrumbHelper
#
# USAGE
# 1. Make sure all of your models have a 'name' attribute.
# (If not, just make an alias in your model that points to another attribute
# class SomeClass < ActiveRecord::Base
# def name
# title
# end
# end
#
# 2. In a view (I put it in app/views/layouts/admin.html.erb) call this:
# <%= get_bread_crumb %>
#
# OPTIONS
# You'll note I am using @breadcrumb_base_override to add a
# link to the root path. This works well for me in admin dashboards,
# since I can use it to link to the root path. If you don't need this, take it out
#
# CREDITS
# by Jack Desert <jackdesert@gmail.com>
# Adapted from:
# https://gist.github.com/sprsquish/445553
# http://www.onlineaspect.com/2010/06/19/breadcrumbs-in-rails/
JOINER = " &raquo; "
def get_bread_crumb
@breadcrumb_base_override = link_to "HOME", root_path
url = controller.env['PATH_INFO']
breadcrumb = []
used_elements = []
elements = url.split('/')
last_index = elements.length - 1
elements.each_with_index do |element, index|
used_elements << element
url = used_elements.join('/')
breadcrumb << if element =~ /^[0-9]+$/
model = elements[index-1].singularize.capitalize.constantize
text = model.find(element).name.humanize rescue element
link_to_if(index < last_index, text, url)
else
link_to_if(index < last_index, element.titleize, url)
end
end
breadcrumb[0] = @breadcrumb_base_override if @breadcrumb_base_override
breadcrumb.join(JOINER).html_safe
rescue
'Breadcrumb Not available'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment