forked from rubocop/rubocop
/
percent_array.rb
60 lines (47 loc) · 1.77 KB
/
percent_array.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
# frozen_string_literal: true
module RuboCop
module Cop
# Common functionality for handling percent arrays.
module PercentArray
private
# Ruby does not allow percent arrays in an ambiguous block context.
#
# @example
#
# foo %i[bar baz] { qux }
def invalid_percent_array_context?(node)
parent = node.parent
parent&.send_type? && parent.arguments.include?(node) &&
!parent.parenthesized? && parent&.block_literal?
end
# Override to determine values that are invalid in a percent array
def invalid_percent_array_contents?(_node)
false
end
def allowed_bracket_array?(node)
comments_in_array?(node) || below_array_length?(node) ||
invalid_percent_array_context?(node)
end
def comments_in_array?(node)
line_span = node.source_range.first_line...node.source_range.last_line
processed_source.each_comment_in_lines(line_span).any?
end
def check_percent_array(node)
array_style_detected(:percent, node.values.size)
return unless style == :brackets || invalid_percent_array_contents?(node)
add_offense(node, message: self.class::ARRAY_MSG) do |corrector|
correct_bracketed(corrector, node)
end
end
def check_bracketed_array(node, literal_prefix)
return if allowed_bracket_array?(node)
array_style_detected(:brackets, node.values.size)
return unless style == :percent
add_offense(node, message: self.class::PERCENT_MSG) do |corrector|
percent_literal_corrector = PercentLiteralCorrector.new(@config, @preferred_delimiters)
percent_literal_corrector.correct(corrector, node, literal_prefix)
end
end
end
end
end