/
underscore_prefixed_variable_name.rb
82 lines (73 loc) · 2.18 KB
/
underscore_prefixed_variable_name.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
71
72
73
74
75
76
77
78
79
80
81
82
# frozen_string_literal: true
module RuboCop
module Cop
module Lint
# This cop checks for underscore-prefixed variables that are actually
# used.
#
# Since block keyword arguments cannot be arbitrarily named at call
# sites, the `AllowKeywordBlockArguments` will allow use of underscore-
# prefixed block keyword arguments.
#
# @example AllowKeywordBlockArguments: false (default)
#
# # bad
#
# [1, 2, 3].each do |_num|
# do_something(_num)
# end
#
# query(:sales) do |_id:, revenue:, cost:|
# {_id: _id, profit: revenue - cost}
# end
#
# # good
#
# [1, 2, 3].each do |num|
# do_something(num)
# end
#
# [1, 2, 3].each do |_num|
# do_something # not using `_num`
# end
#
# @example AllowKeywordBlockArguments: true
#
# # good
#
# query(:sales) do |_id:, revenue:, cost:|
# {_id: _id, profit: revenue - cost}
# end
#
class UnderscorePrefixedVariableName < Cop
MSG = 'Do not use prefix `_` for a variable that is used.'.freeze
def join_force?(force_class)
force_class == VariableForce
end
def after_leaving_scope(scope, _variable_table)
scope.variables.each_value do |variable|
check_variable(variable)
end
end
def check_variable(variable)
return unless variable.should_be_unused?
return if variable.references.none?(&:explicit?)
return if allowed_keyword_block_argument?(variable)
node = variable.declaration_node
location = if node.match_with_lvasgn_type?
node.children.first.source_range
else
node.loc.name
end
add_offense(nil, location: location)
end
private
def allowed_keyword_block_argument?(variable)
variable.block_argument? &&
variable.keyword_argument? &&
cop_config['AllowKeywordBlockArguments']
end
end
end
end
end