hackdiary

Using Omnigraffle to visualise Rails model associations

This week I'm doing some Rails consulting work for a company that's already developed and deployed a major application. Getting to know a new codebase takes a little time and every diagram or visualisation helps. To help me understand their ActiveRecord model relationships, I knocked together a quick script to scan the associations between models and output it in the Graphviz DOT format.

A quick Omnigraffle import later, and I get useful diagrams like this fragment from the BBC Programme Catalogue codebase:

Here's the code, ready for running from the top of any Rails project (ymmv, etc):

#!/usr/bin/env ruby
require "config/environment"
Dir.glob("app/models/*rb") { |f|
    require f
}
puts "digraph x {"
Dir.glob("app/models/*rb") { |f|
    f.match(/\/([a-z_]+).rb/)
    classname = $1.camelize
    klass = Kernel.const_get classname
    if klass.superclass == ActiveRecord::Base
        puts classname
        klass.reflect_on_all_associations.each { |a|
            puts classname + " -> " + a.name.to_s.camelize.singularize + " [label="+a.macro.to_s+"]"
        }
    end
}
puts "}"
rails Posted by Matt Biddulph at August 2, 2006 02:57 PM