Skip to content

Instantly share code, notes, and snippets.

@TMorgan99
Created April 17, 2009 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TMorgan99/97293 to your computer and use it in GitHub Desktop.
Save TMorgan99/97293 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
## Shows model relationships on the given RoR app.
puts ARGV
Dir.chdir( ARGV.shift || '.' ) do
require 'config/environment'
finder = 'find app/models -type f -name \*.rb -print0 |xargs -0 -- grep ActiveRecord::Base |sort'
dot = []
%x[#{finder}].map do |line|
line =~ /class (\w+)/
model = Object.const_get $1 # get the class from string
puts "#{model}"
relation_shown = nil
o = []
model.reflect_on_all_associations. each do |assoc|
next unless assoc.options[:through].nil? # a :through relation will have the :has_many elsewhere.
related = (
assoc.options[:class_name] || # if :class_name is specified in the assoc
assoc.name.to_s.classify # else use assoc name as class_name
)
# This model relates to the related model, by :macro ( belongs_to, has_many ... )
o << " #{assoc.macro} #{related}"
relation_shown = true
dot << "#{model} -> #{related} \n" ## if assoc.macro == 'has_many' #//[label=#{assoc.macro}]\n"
end
o << " (no relations)" if relation_shown.nil?
puts o.sort.uniq
end
IO.popen('dot -Tpng -omodels.png', 'w') do |io|
io.write <<__DOT
digraph x {
node [ shape=box, color=gray, fontname="Sans", fontsize=10 ]
edge [ color=gray, arrowhead=none ]
#{dot}
}
__DOT
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment