Model Your Models
August 9th, 2006
Ever wish you could visualize the relationships in your Rails application? You could grab a marker and head to the whiteboard. Or, you could have Ruby create a little graphical representation of your application in less time than it takes your finger to come off the Return key.
I originally found this trick on hackdiary, and I’ve modified it into a rake task.
Ingredients:
- Ruby on Rails
- OmniGraffle (or any diagraming application that can open *.dot files)
- Knowledge of Rake
- A backup of your app, just in case (you are using Subversion, aren’t you?)
Here’s the code:
desc "Create a graphical diagram of this app's models"
task :graph do
require "config/environment"
Dir.glob("app/models/*rb") { |f|
require f
}
File.open("#{RAILS_ROOT}/models.dot", 'w') do |file|
file.write "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|
file.write classname + " -> " + a.name.to_s.camelize.singularize + " [label="+a.macro.to_s+"]"
}
end
}
file.write "}"
end
end
To use:
- Create a file in
RAILS_ROOT/lib/tasks/graph.rake
. - Drop in the above code.
- Go to your terminal and (in the root of your application) type
rake graph
. - Now open OmniGraffle, and go to File > Open. Look for the file in your RAILS_ROOT directory called
models.dot
. Open it up.
Here’s what I got when I ran this script on SliceOfSites:
Link love goes to hackdiary, who originally posted this tip.
August 10th, 2006 at 04:03 AM Nice, very nice! This will come in handy for clients that want to better understand such aspects of what we are doing with their content. I know I have had several curious questions about how it all works. This would be great to show them. Thanks Ryan!
August 10th, 2006 at 05:13 AM Great work. I'm delighted to see my code reworked into a much more useful, accessible shape. A rake task is a great idea.
August 10th, 2006 at 01:41 PM Thanks again for the tip Matt.
August 15th, 2006 at 06:50 AM If only omnigraffle was a bit better at arranging things.... http://iamrice.org/files/rgraph.gif
August 15th, 2006 at 07:23 AM Wow - Damien that is an amazing set of relationships you have there :)
September 2nd, 2006 at 03:14 AM OmniGraffle, only available on mac, in Window to generate PNG files from "models.dot" visit following link and download "WinGraphviz.msi" http://home.so-net.net.tw/oodtsen/wingraphviz/index.htm on bottom of the page of that site, there is example test.vbs script code. It can use to generate PNG file, Note: on that script section"Sample data of DOT" just put your models.dot data Thanks for this cool tricks ......