Skip to content

Commit

Permalink
Merge pull request #8170 from koic/support_autocorrect_for_regexp_as_…
Browse files Browse the repository at this point in the history
…condition

Support autocorrection for `Lint/RegexpAsCondition`
  • Loading branch information
koic committed Jun 21, 2020
2 parents 4eb8212 + ce67bd8 commit 5681925
Show file tree
Hide file tree
Showing 5 changed files with 16 additions and 3 deletions.
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

0 comments on commit 5681925

Please sign in to comment.