Tool/gem to find commented code
Asked Answered
S

3

6

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.

Spirant answered 14/11, 2012 at 23:39 Comment(2)
What differentiates "code" versus "comment text"?Superlative
I guess if it compiles its code otherwise its a comment :)Spirant
C
1

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.

Chalky answered 14/11, 2012 at 23:49 Comment(2)
Most (if not all) matched ruby lines will also fail.Boz
True, but if the error raised is NoMethod maybe is possible to assume that the string is rb code. Just shooting a wild idea.Chalky
A
1

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 #

Aircrew answered 15/11, 2012 at 0:54 Comment(0)
P
0

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
Poppas answered 4/9, 2024 at 12:0 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.