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:

  1. Create a file in RAILS_ROOT/lib/tasks/graph.rake.
  2. Drop in the above code.
  3. Go to your terminal and (in the root of your application) type rake graph.
  4. 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:

models.jpg

Link love goes to hackdiary, who originally posted this tip.


6 Responses to “Model Your Models”

  1. Robert Says:
    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!
  2. Matt Biddulph Says:
    Great work. I'm delighted to see my code reworked into a much more useful, accessible shape. A rake task is a great idea.
  3. Ryan Says:
    Thanks again for the tip Matt.
  4. Damien Tanner Says:
    If only omnigraffle was a bit better at arranging things.... http://iamrice.org/files/rgraph.gif
  5. Ryan Says:
    Wow - Damien that is an amazing set of relationships you have there :)
  6. Raru Says:
    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 ......

Leave a Reply