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

Support autocorrection for Lint/RegexpAsCondition #8170

Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -9,6 +9,7 @@
* [#8148](https://github.com/rubocop-hq/rubocop/pull/8148): Support autocorrection for `Style/MultilineTernaryOperator`. ([@koic][])
* [#8151](https://github.com/rubocop-hq/rubocop/pull/8151): Support autocorrection for `Style/NestedTernaryOperator`. ([@koic][])
* [#8142](https://github.com/rubocop-hq/rubocop/pull/8142): Add `Lint/ConstantResolution` cop. ([@robotdana][])
* [#8170](https://github.com/rubocop-hq/rubocop/pull/8170): Support autocorrection for `Lint/RegexpAsCondition`. ([@koic][])

### Bug fixes

Expand Down
1 change: 1 addition & 0 deletions config/default.yml
Expand Up @@ -1677,6 +1677,7 @@ Lint/RegexpAsCondition:
The regexp literal matches `$_` implicitly.
Enabled: true
VersionAdded: '0.51'
VersionChanged: '0.86'

Lint/RequireParentheses:
Description: >-
Expand Down
4 changes: 2 additions & 2 deletions docs/modules/ROOT/pages/cops_lint.adoc
Expand Up @@ -2524,9 +2524,9 @@ end

| Enabled
| Yes
| No
| Yes
| 0.51
| -
| 0.86
|===

This cop checks for regexp literals used as `match-current-line`.
Expand Down
6 changes: 6 additions & 0 deletions lib/rubocop/cop/lint/regexp_as_condition.rb
Expand Up @@ -23,6 +23,12 @@ class RegexpAsCondition < Cop
def on_match_current_line(node)
add_offense(node)
end

def autocorrect(node)
lambda do |corrector|
corrector.replace(node, "#{node.source} =~ $_")
end
end
end
end
end
Expand Down
7 changes: 6 additions & 1 deletion spec/rubocop/cop/lint/regexp_as_condition_spec.rb
Expand Up @@ -5,12 +5,17 @@

let(:config) { RuboCop::Config.new }

it 'registers an offense for a regexp literal in `if` condition' do
it 'registers an offense and corrects for a regexp literal 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
Expand Down