Created
May 24, 2021 13:42
-
-
Save guicattani/bc1840e637a2f4038da24098b4b3f712 to your computer and use it in GitHub Desktop.
Find commented code in Ruby
This file contains hidden or 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 | |
| ARGV.each do |filename| | |
| fileobject = File.new(filename, "r") | |
| next if fileobject.nil? | |
| occurences = 0 | |
| lines = fileobject.readlines | |
| lines.each do |line| | |
| next unless line.match(/\A *#.+\n/) | |
| if line.match(/.*[print|puts] ["'].*["']\n/) | |
| occurences+=1 | |
| next | |
| end | |
| line = line.gsub(/\n/,"") | |
| line = line.sub(/\A *# */," ") | |
| begin | |
| eval(line) | |
| rescue SyntaxError => e | |
| occurences+=1 if e.message.match(/.*unexpected end.*|.*void.*/) | |
| next | |
| rescue | |
| occurences+=1 | |
| next | |
| end | |
| next if line.match(/ *#.*/) # double comments | |
| occurences+=1 | |
| end | |
| next if occurences == 0 | |
| percentage = (occurences/Float(lines.count)).truncate(4) * 100 | |
| next if percentage < 10 | |
| pp "#{fileobject.path} has ~#{occurences}/#{lines.count}(#{percentage}%) lines with commented code" | |
| fileobject.close() | |
| local_variables.each { |e| eval("#{e} = nil") } | |
| end |
Author
This worked for me
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
Author
Thanks for the contribution @HMADAHMD! It's good to have a Ruby alternative!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Quick disclaimer, this script is by no means exhaustive!
You can run it with
find */ -name *.rb -type f | xargs ruby ./find_commented_code.arb