Skip to content

Instantly share code, notes, and snippets.

@TMorgan99
Created March 27, 2009 20:59
Show Gist options
  • Save TMorgan99/86897 to your computer and use it in GitHub Desktop.
Save TMorgan99/86897 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
## Shows model relationships on the given RoR app.
## add --help
## ?? add --belongs to filter out only given macros
## put message 'nothing relates' if models but no associations found.
puts ARGV
Dir.chdir( ARGV.shift || '.' ) do
# Load the app.
# Gives us the inflections and ability to find valid class names.
require 'config/environment'
# # look for classes derived from ActiveRecord
# finder = 'grep ActiveRecord::Base app/models/*.rb'
finder = 'find app/models -type f -name \*.rb -print0 |xargs -0 -- grep ActiveRecord::Base |sort'
%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|
assoc.options[:through].nil? or next # 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
end
o << " (no relations)" if relation_shown.nil?
puts o.sort.uniq
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment