Dependency Sorting in Ruby with TSort

If you write Ruby with any regularity, you've probably experienced the dependency-managing wonders of Bundler. What you didn't know, however, was that you can use the same dependency-sorting goodness within your own application in other contexts.

Say Hello to TSort

TSort is a module included in the Ruby standard library for executing topological sorts. Under the hood, Bundler uses TSort to detangle your gems' web of dependencies. Managing gem dependencies, however, is just the tip of the iceberg when it comes to processes that can benefit from topological sorting. With just a trivial amount of work, you can put its awesome power to work in your own projects.

Use Case: Adding Sample Data to a Database

Imagine we have a single task that must populate a database with several records. But life isn't easy; our records have associations with each other as demonstrated in the pseudocode below.

The Problem

If we ran the pseudocode above, it would obviously blow up with NameErrors because multiple records include associational references to records that are yet to be created.

In this simple, contrived example, it would be straightforward to manually sort the statements to ensure that we insert the records that others depend on first. But when our dependency relationships are more complex, or when we simply have a much larger number of records, manual sorting is out of the question. (Who ever liked doing anything manually anyway?)

The Solution

Enter TSort. We can use TSort to programmatically determine an order that these records can be inserted successfully.

The most straightforward fashion of using TSort is through the creation and subsequent sorting of a dependency hash where keys represent an object and values are arrays of references to the objects on which the key object depends.

So if skiing depends on snow, and snow depends on clouds and cold, our dependency hash might look like this:

Once we've created our tsortable dependency hash, the hard work is over. TSort the hash for great justice and we're left with an array of insert processes that can be executed in order without catastrophe.

TSort is an incredibly powerful and easy-to-use tool for organizing dependency relationships. So next time you find yourself struggling with dependency ordering in Ruby, rest assured. TSort is only a click away.