Skip to content

Instantly share code, notes, and snippets.

@henrik
Created August 26, 2009 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save henrik/175523 to your computer and use it in GitHub Desktop.
Save henrik/175523 to your computer and use it in GitHub Desktop.
Simple breadcrumb trail for Rails. MIT license. Will likely spec and pluginize later.
You are here:
<%= trail.to_html(response) %>
class ApplicationController < ActionController::Base
before_filter :trail
def self.trail(&block)
# Controller-level trails become filters so they run inside the
# request/response cycle, where internationalization etc works.
# instance_exec means you can use path helpers.
before_filter {|controller| controller.instance_exec(controller.send(:trail), &block) }
end
trail {|t| t << ['Home', '/'] }
protected
def trail
@breadcrumb_trail ||= BreadcrumbTrail.new
end
helper_method :trail
class BreadcrumbTrail
def initialize
@crumbs = []
end
def <<(crumb)
@crumbs << crumb
end
def append(crumbs)
@crumbs += crumbs
end
def to_html(response)
template = response.template
@crumbs.map { |crumb|
text, url = Array(crumb)
last_crumb = @crumbs.last
template.instance_eval {
link_to_unless((crumb == last_crumb || url.blank?), h(text), url) {|text| content_tag(:span, text) }
}
}.join(" &gt; ")
end
end
end
class ItemsController < ApplicationController
trail {|t| t << ['Items', '/items'] }
def show
trail << ['Specific item from controller', '/items/123']
end
end
<%
trail << ['Specific item from view', '/items/123']
# Note that since layouts are rendered after their child template,
# trails appended in a layout will currently come after those
# appended in the child templates.
%>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment