acts_as_breadcrumbs
Breadcrumbs on Rails
In a few programs that I have worked on in recent months I have had a need to build models using acts_as_tree either for building a URL, Breadcrumbs, or a Location String for picking inventory. They all have something in common, in order to build the string properly they relied on acts_as_tree and used two recursive methods to traverse the tree to essentially create a breadcrumbs pattern in one for or another.
“You Are Here”
So I decided to extract the meaningful bits of code and create a small plugin that adds breadcrumbs methods to ActiveRecord. The result is acts_as_breadcrumbs.
It’s very easy to use, provide a “breadcrumbs” column to store the resulting breadcrumbs string (yes store, we’re not building it on the fly), and provide a basename column to build the string.
Docs
http://breadcrumbs.rubyforge.org
Installation
- script/plugin install svn://rubyforge.org/var/svn/breadcrumbs/trunk/acts_as_breadcrumbs
Examples
acts_as_tree
acts_as_breadcrumbs(:attr => :location_string)
end
some_location = Location.new(:name => "RM03", :parent => first_floor, :description => "Room 3 on the First Floor")
some_location.location_string #=> "HQ:FL01:RM03"
The above example creates an address for picking inventory.
acts_as_tree
acts_as_breadcrumbs(:attr => :chain_o_command, :separator => " > ")
end
mueller = Soldier.new(:name => "LTC Mueller", :parent => stanley)
mueller.chain_o_command #=> "General Hailstone > Colonel Stanley > LTC Mueller"
This example creates a chain of command excluding the root object(The President).
include ActionView::Helpers::TagHelper
acts_as_tree
acts_as_breadcrumbs(:attr => :url, :basename => :slug, :separator => "/")
acts_as_breadcrumbs(:basename => :link, :separator => " > ")
# from urlnameable
def slug
t = self.title.to_s.downcase.strip.gsub(/[^-\s[:alnum:]]/, ’’).squeeze(’ ‘).tr(’ ‘, ‘‘)
(t.blank?) ? ’_’ : t
end
def link
content_tag ‘a’, self.title, :href => "#{self.url}"
end
end
baz = WebPage.create(:title => "Baz", :parent => bar)
baz.url #=> ‘foo/bar/baz’
baz.breadcrumbs #=> ’<a href="foo">Foo</a> > <a href="foo/bar">Bar</a> > <a href="foo/bar/baz">Baz</a>’
The last example uses two breadcrumbs attributes, one to generate a URL (yes it’s a hack but fun for example purposes) and another to create a breadcrumbs string.
Note: in my examples I use hypothetical existing objects
Bug Warning
This is the first release, so please let me know if you find bugs. Achtung! if you set the parent_id = id you get a cartesian product (ie. a never ending loop), I might add a validator to ensure parent_id != id.
Trackbacks
Use the following link to trackback from your own site:
http://www.actsasflinn.com/trackbacks?article_id=acts_as_breadcrumbs&day=02&month=05&year=2007


