-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
block_comments.rb
70 lines (61 loc) · 1.83 KB
/
block_comments.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop looks for uses of block comments (=begin...=end).
#
# @example
# # bad
# =begin
# Multiple lines
# of comments...
# =end
#
# # good
# # Multiple lines
# # of comments...
#
class BlockComments < Cop
include RangeHelp
MSG = 'Do not use block comments.'.freeze
BEGIN_LENGTH = "=begin\n".length
END_LENGTH = "\n=end".length
def investigate(processed_source)
processed_source.each_comment do |comment|
next unless comment.document?
add_offense(comment)
end
end
def autocorrect(comment)
eq_begin, eq_end, contents = parts(comment)
lambda do |corrector|
corrector.remove(eq_begin)
unless contents.length.zero?
corrector.replace(contents,
contents.source
.gsub(/\A/, '# ')
.gsub(/\n\n/, "\n#\n")
.gsub(/\n(?=[^#])/, "\n# "))
end
corrector.remove(eq_end)
end
end
private
def parts(comment)
expr = comment.loc.expression
eq_begin = expr.resize(BEGIN_LENGTH)
eq_end = eq_end_part(comment, expr)
contents = range_between(eq_begin.end_pos, eq_end.begin_pos)
[eq_begin, eq_end, contents]
end
def eq_end_part(comment, expr)
if comment.text.chomp == comment.text
range_between(expr.end_pos - END_LENGTH - 1, expr.end_pos - 2)
else
range_between(expr.end_pos - END_LENGTH, expr.end_pos)
end
end
end
end
end
end