Archives for the month of: June, 2007

Sometimes, when it’s getting late, after a few beers and when you have more than a couple of Active Records in your project, things can get a bit blurry. What is linked to what? Did I make that a belong_to or a has_many? Clearly, the bigger picture can elude you.

Fortunately, I just discovered (thanks to Matt Biddulph) some way to generate a quick and easy diagram showing how your active records play with each other. But don’t start thinking I needed this because I had a beer. I did not. Or did I? Anyway, it’s fortunately pretty simple.

  1. First you’ll need graphviz. If you’re running the right O/S it’s as straightforward as ‘apt-get install graphviz’. The two of you running Fedora can replace apt-get by yum, I’m guessing it would work just as well. For Windows and Mac users, it’s just a download.
  2. Save the Ruby script reproduced below in a ‘graph.rb’ file located at the root of your Rails project.
  3. Run ‘ruby graph.rb | dot -Tpng -ograph.png’. It won’t work with the wrong O/S (understand Windows). You’ll have to save the output of the script in a file and then run the second part of the command on that file. Also if you’re dorky enough to have some ‘puts’ in your ActiveRecord you’ll have to save the output in a file as well and clean that up.
  4. Open graph.png.

Here is the promised script (slight improvements from the original).

#!/usr/bin/env ruby

require "config/environment"

Dir.glob("app/models/*rb") { |f| require f }puts "digraph x {"

Dir.glob("app/models/*rb") do |f|

classname = f.match(//([a-z_]+).rb/)[1].camelize

klass = Kernel.const_get classname

if ActiveRecord::Base >= klass

puts classname

klass.reflect_on_all_associations.each do |a|

label = (a.macro.to_s =~ /many/) ? "*" : "1"

puts "#{classname} -> #{a.name.to_s.camelize.singularize} [label="#{label}"]"

end

end

end

puts "}"

And here is an example of the result:

Run BunnyThere are basically two ways to shoot yourself in the foot these days:

Anybody willing to develop a peer-to-peer extension for Windows Media Player out there? I bet that would be a lot of fun.

Follow

Get every new post delivered to your Inbox.