ruby inject and category breadcrumbs

In addition to mapping out the Mandelbrot set, ruby’s inject method can also be used to easily find and/or create nested categories given a breadcrumb path.

Assuming Category is a Ruby on Rails ActiveRecord class that acts_as_tree, and breadcrumbs is an array of breadcrumb strings, e.g. breadcrumbs = ['Widgets', 'Green Widgets', '14V Widgets'] :

def find_or_create_category( breadcrumbs )
  id = breadcrumbs.inject(nil) { |pid,name| Category.
     find_or_create_by_parent_id_and_name(pid,name).id }
  id && Category.find(id)
end

The final “id && Category.find(id)” is to have the function return nil in case breadcrumbs is empty.

This returns the final Category object if it exists, and creates any or all components of the path as needed.

Share:
  • del.icio.us
  • Reddit
  • Technorati
  • Twitter
  • Facebook
  • Google Bookmarks
  • HackerNews
  • PDF
  • RSS
This entry was posted in programming. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.