Using TSort in Ruby for Topological Sorting of ActiveRecord Models

Recently, I was building a project list application in Rails and I needed to be sure that sub-projects showed up in the list somewhere below their parents.

A topological sort does just what I needed, and I was pleased to discover that Ruby ships with a TSort module.  Here is how I extended Array to allow sorting of Projects:

(Aside: I later post-processed the list to indent sub-projects and position them just below their parents. This post-processing was made easier by the fact that all sub-projects were already somewhere below their parents in the list.)

Comments