Using Omnigraffle to visualise Rails model associations

August 2nd, 2006  |  Published in rails  |  1 Comment

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 "}"

 
close Reblog this comment
blog comments powered by Disqus