-
-
Save TMorgan99/86897 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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