Class: Cleanio::Remover
- Inherits:
-
Object
- Object
- Cleanio::Remover
- Defined in:
- lib/cleanio.rb
Class Method Summary collapse
- .audit_comments(file_path, content) ⇒ Object
- .clean(file_path, audit: false) ⇒ Object
- .extract_comments(content) ⇒ Object
- .process_comment_line(line, col) ⇒ Object
- .process_comments(content, comments) ⇒ Object
- .process_file(file_path, audit: false) ⇒ Object
- .remove_comments(content) ⇒ Object
- .remove_empty_lines(content) ⇒ Object
- .validate_file_extension(file_path) ⇒ Object
Class Method Details
.audit_comments(file_path, content) ⇒ Object
34 35 36 37 38 39 40 41 42 |
# File 'lib/cleanio.rb', line 34 def self.audit_comments(file_path, content) comments = extract_comments(content) puts "File: #{file_path}" unless comments.empty? comments.each do |(pos, _, tok, _)| line, = pos puts " Line #{line}: #{tok.strip}" end end |
.clean(file_path, audit: false) ⇒ Object
8 9 10 11 12 13 14 15 16 |
# File 'lib/cleanio.rb', line 8 def self.clean(file_path, audit: false) if File.directory?(file_path) Dir.glob("#{file_path}/**/*.rb").each do |file| process_file(file, audit: audit) end else process_file(file_path, audit: audit) end end |
.extract_comments(content) ⇒ Object
50 51 52 |
# File 'lib/cleanio.rb', line 50 def self.extract_comments(content) Ripper.lex(content).select { |_pos, type, _tok, _| type == :on_comment } end |
.process_comment_line(line, col) ⇒ Object
64 65 66 67 68 69 70 |
# File 'lib/cleanio.rb', line 64 def self.process_comment_line(line, col) if line[col..].strip.start_with?("#") "#{line[0...col].rstrip}\n" else "\n" end end |
.process_comments(content, comments) ⇒ Object
54 55 56 57 58 59 60 61 62 |
# File 'lib/cleanio.rb', line 54 def self.process_comments(content, comments) comments.sort_by { |(pos, _, _, _)| [pos[0], pos[1]] }.reverse.each do |(pos, _, _, _)| line, col = pos lines = content.lines lines[line - 1] = process_comment_line(lines[line - 1], col) content = lines.join end content end |
.process_file(file_path, audit: false) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/cleanio.rb', line 18 def self.process_file(file_path, audit: false) validate_file_extension(file_path) file_content = File.read(file_path) if audit audit_comments(file_path, file_content) else content_cleaned = remove_comments(file_content) File.write(file_path, content_cleaned) end end |
.remove_comments(content) ⇒ Object
44 45 46 47 48 |
# File 'lib/cleanio.rb', line 44 def self.remove_comments(content) comments = extract_comments(content) content = process_comments(content, comments) remove_empty_lines(content) end |
.remove_empty_lines(content) ⇒ Object
72 73 74 |
# File 'lib/cleanio.rb', line 72 def self.remove_empty_lines(content) content.gsub(/^\s*$\n/, "") end |
.validate_file_extension(file_path) ⇒ Object
30 31 32 |
# File 'lib/cleanio.rb', line 30 def self.validate_file_extension(file_path) raise "Only Ruby files are supported" unless file_path.end_with?(".rb") end |