rrg: visualize the require hierarchy in Ruby projects
Yesterday I was hacking on some Ruby code and getting a weird error which I thought was caused by mutually recursive require statements (i.e. A requires B, and B requires A). Later I realized that this is not an issue in Ruby, since the intepreter keeps track of what has already been required and will not enter a loop. But during the investigation I came up with something that turned out to be useful.
rrg will read the source code of a Ruby project and generate a graph based on the require statements in the code; nodes represent the source files and an arrow from A to B means that A contains a `require ‘B’` statement.
From the README
:
Just run
rrg
at the root of your project.rrg
will parse the code insidelib/
, and generate a graph description in the Graphviz format. You can pipe the output to Graphviz directly, or store it in a file and process it to generate an image.If you call
rrgv
instead, it will automatically process the graph with Graphviz, generate a PNG image, and open it.
Let’s see some examples. First the classical “analysing itself” example, the require graph for rrg
itself:
Not very interesting, since all of the logic is currently in the main binary and not on library code. But 1) when I do the refactorings I want to, there will be more library code and 2) while writing this I implemented also parsing scripts in bin/
.
Now chake which is a slightly larger project:
An even larger (but still not that big) project, gem2deb:
Note that these visualizations may not be accurate representations of the actual source code. In Ruby, nothing stops one from implementing class A::B
in lib/x/y.rb
, but most reasonable code will make sure that filenames and the classes namespaces actually match.
If you are working on a sane codebase, though, visualizing graphs like this helps understand the general structure of the code and perceive possible improvements. The gem2deb
graph gave me some ideas already and I didn’t even paid much attention to it yet.