forked from rubocop/rubocop
-
Notifications
You must be signed in to change notification settings - Fork 2
/
regexp_as_condition.rb
37 lines (32 loc) · 933 Bytes
/
regexp_as_condition.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
# frozen_string_literal: true
module RuboCop
module Cop
module Lint
# Checks for regexp literals used as `match-current-line`.
# If a regexp literal is in condition, the regexp matches `$_` implicitly.
#
# @example
# # bad
# if /foo/
# do_something
# end
#
# # good
# if /foo/ =~ $_
# do_something
# end
class RegexpAsCondition < Base
include IgnoredNode
extend AutoCorrector
MSG = 'Do not use regexp literal as a condition. ' \
'The regexp literal matches `$_` implicitly.'
def on_match_current_line(node)
return if node.ancestors.none?(&:conditional?)
return if part_of_ignored_node?(node)
add_offense(node) { |corrector| corrector.replace(node, "#{node.source} =~ $_") }
ignore_node(node)
end
end
end
end
end