Skip to content

Instantly share code, notes, and snippets.

@cantino
Created January 29, 2010 19:50
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 cantino/290045 to your computer and use it in GitHub Desktop.
Save cantino/290045 to your computer and use it in GitHub Desktop.
# Ruby's TSort requires that you implement
# tsort_each_node and tsort_each_child. I
# extend Array so that it knows how to
# TSort instances of Project, which has a
# child_project_id pointing to another
# Project.
require 'tsort'
class Array
include TSort
alias tsort_each_node each
def tsort_each_child(node, &block)
if node.is_a?(Project)
[node.child_project].each(&block) if node.child_project?
else
node.each(&block) if node
end
end
end
# Then I can topologically sort a user's projects like so:
sorted_projects = current_user.projects.tsort
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment