Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix an incorrect autocorrect for Lint/RegexpAsCondition #11351

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -0,0 +1 @@
* [#11351](https://github.com/rubocop/rubocop/pull/11351): Fix an incorrect autocorrect for `Lint/RegexpAsCondition` when using regexp literal with bang. ([@koic][])
6 changes: 6 additions & 0 deletions lib/rubocop/cop/lint/regexp_as_condition.rb
Expand Up @@ -17,13 +17,19 @@ module Lint
# 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
Expand Down
19 changes: 19 additions & 0 deletions spec/rubocop/cop/lint/regexp_as_condition_spec.rb
Expand Up @@ -14,12 +14,31 @@
RUBY
end

it 'registers an offense and corrects for a regexp literal with bang in `if` condition' do
expect_offense(<<~RUBY)
if !/foo/
^^^^^ Do not use regexp literal as a condition. The regexp literal matches `$_` implicitly.
end
RUBY

expect_correction(<<~RUBY)
if !/foo/ =~ $_
end
RUBY
end

it 'does not register an offense for a regexp literal outside conditions' do
expect_no_offenses(<<~RUBY)
/foo/
RUBY
end

it 'does not register an offense for a regexp literal with bang outside conditions' do
expect_no_offenses(<<~RUBY)
!/foo/
RUBY
end

it 'does not register an offense for a regexp literal with `=~` operator' do
expect_no_offenses(<<~RUBY)
if /foo/ =~ str
Expand Down