Report abuse

#
# Modified by EmmanuelOga.blogspot.com, converted to a task
# Original in http://www.hackdiary.com/archives/000093.html
#
# Requirements: dot (http://www.graphviz.org/)
#
# Usage: Drop in lib/tasks of your rails app. rake doc:reflex
#        See reflections.png in doc
#
namespace :doc do

  desc "Graph model reflections"
  task(:reflex => :environment) do

    filename= "#{RAILS_ROOT}/doc/reflections.dot"

    File.open(filename, "w+") do |file|
      file << "digraph x {\n"

      Dir.glob("#{RAILS_ROOT}/app/models/*rb") do |f|

        f.match(/\/([a-z_]+).rb/)
        classname = $1.camelize
        klass = Kernel.const_get classname

        if klass.superclass == ActiveRecord::Base
          file << classname << "\n"
          klass.reflect_on_all_associations.each do |a|
            file << classname << " -> " << a.name.to_s.camelize.singularize 
            file << " [label=#{a.macro.to_s}]\n"
          end
        end
      end

      file << "}"
    end

    system("dot -Tpng -O #{filename}")

  end 
end