/
code_length.rb
59 lines (45 loc) · 1.5 KB
/
code_length.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
# frozen_string_literal: true
module RuboCop
module Cop
# Common functionality for checking length of code segments.
module CodeLength
extend ExcludeLimit
MSG = '%<label>s has too many lines. [%<length>d/%<max>d]'
exclude_limit 'Max'
private
def message(length, max_length)
format(MSG, label: cop_label, length: length, max: max_length)
end
def max_length
cop_config['Max']
end
def count_comments?
cop_config['CountComments']
end
def count_as_one
Array(cop_config['CountAsOne']).map(&:to_sym)
end
def check_code_length(node)
# Skip costly calculation when definitely not needed
return if node.line_count <= max_length
calculator = build_code_length_calculator(node)
length = calculator.calculate
return if length <= max_length
location = node.casgn_type? ? node.loc.name : node.loc.expression
add_offense(location, message: message(length, max_length)) { self.max = length }
end
# Returns true for lines that shall not be included in the count.
def irrelevant_line(source_line)
source_line.blank? || !count_comments? && comment_line?(source_line)
end
def build_code_length_calculator(node)
Metrics::Utils::CodeLengthCalculator.new(
node,
processed_source,
count_comments: count_comments?,
foldable_types: count_as_one
)
end
end
end
end