Created
August 24, 2012 08:39
-
-
Save bkutil/3447593 to your computer and use it in GitHub Desktop.
Simple script for scanning a file for possible model references, then filtering out those which no longer exist in app/models.
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 | |
require 'rubygems' | |
require 'machete' | |
rails_root = ARGV[0] | |
file = ARGV[1] | |
if rails_root.nil? || !File.exists?(rails_root) || file.nil? || !File.exists?(file) | |
warn "Usage: dead_models <rails root> <source file>" | |
exit(1) | |
end | |
source = File.read(file) | |
def model_pattern | |
patterns = [ | |
'SendWithArguments<name ^= :find, receiver = ConstantAccess>', | |
'SendWithArguments<name ^= :destroy, receiver = ConstantAccess>', | |
'SendWithArguments<name ^= :create, receiver = ConstantAccess>', | |
'SendWithArguments<name ^= :update, receiver = ConstantAccess>', | |
'SendWithArguments<name ^= :save, receiver = ConstantAccess>', | |
'SendWithArguments<name ^= :reload, receiver = ConstantAccess>', | |
].join("|") | |
end | |
# Stolen from rails sources | |
def underscore(camel_cased_word) | |
word = camel_cased_word.to_s.dup | |
word.gsub!(/::/, '/') | |
word.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2') | |
word.gsub!(/([a-z\d])([A-Z])/,'\1_\2') | |
word.tr!("-", "_") | |
word.downcase! | |
word | |
end | |
nodes = Machete.find(source.to_ast, model_pattern) | |
calls = nodes.map { |node| [file, node.receiver.line, node.receiver.name.to_s, "#{underscore(node.receiver.name.to_s)}.rb"] } | |
calls.each do |call| | |
ref_file, ref_line, model, model_file = *call | |
path = File.join(rails_root, "app", "models", model_file) | |
puts "Model #{model} referenced from #{ref_file}:#{ref_line} is probably dead." unless File.exists?(path) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment