Reputation: 1570
Over the course of our project with multiple developers and styles, we have some tests and code that are commented out. Is there an easy way to find all code that is commented out?
The tool should be smart enough to find out that it is ruby code that is being commented not, real comments.
At this point I can only think of grep like grep #
, but it should be something smarter and less manual.
Upvotes: 6
Views: 261
Reputation: 1
Run the following script in your rails console or irb. Also. you can create a file and paste it there, then run ruby your_file_name.rb It will give you all files where is commented code.
require 'find'
directory = './' # Change this to your project directory
code_patterns = [
/^\s*#\s*\w+\s*=\s*/,
/^\s*#\s*\w+\s*\.\w+\s*/,
/^\s*#\s*def\s+\w+/,
/^\s*#\s*end\b/,
/^\s*#\s*if\b/,
/^\s*#\s*class\b/,
/^\s*#\s*module\b/,
/^\s*#\s*do\b/,
/^\s*#\s*{.*}/,
/^\s*#\s*begin\b/,
/^\s*#\s*rescue\b/,
]
def commented_code?(line, patterns)
patterns.any? { |pattern| line.match(pattern) }
end
files_with_commented_code = []
Find.find(directory) do |path|
next unless File.file?(path)
next unless path.end_with?('.rb') # Only consider Ruby files
File.foreach(path).with_index do |line, line_num|
if commented_code?(line, code_patterns)
files_with_commented_code << path unless files_with_commented_code.include?(path)
puts "File: #{path}, Line #{line_num + 1}: #{line.strip}"
end
end
end
if files_with_commented_code.empty?
puts "No files with commented-out code found."
else
puts "\nFiles with commented-out code:"
files_with_commented_code.each { |file| puts file }
end
Upvotes: 0
Reputation: 37517
It seems you'll need a looks_like_ruby
method so you can do this:
puts line if line =~ /^\s+#/ && looks_like_ruby(line)
A quick and dirty implementation (off the top of my head)
def looks_like_ruby(text)
text =~ Regexp.union((Kernel.methods + Object.methods).uniq.map(&:to_s))
end
Not perfect, but better than grepping for #
Upvotes: 1
Reputation: 7735
This may be ugly but I think you can inspect each ".rb" file with a rake task, line per line, matching it with a regexp (something like /#.*\n/), and run an eval("matching_string")
on each match. If the comment isn't ruby code it will simply fail.
Upvotes: 1