Skip to content

Commit

Permalink
[Fix rubocop#55] Fix an incorrect autocorrect for `Performance/Regexp…
Browse files Browse the repository at this point in the history
…Match`

Fixes rubocop#55.

This PR fixes an incorrect autocorrect for `Performance/RegexpMatch` cop
when using `str.=~(/regexp/)`.
  • Loading branch information
koic committed May 16, 2020
1 parent 105cbc8 commit 6d655c9
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 3 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
* [#105](https://github.com/rubocop-hq/rubocop-performance/pull/105): Add new `Performance/DeletePrefix` and `Performance/DeleteSuffix` cops. ([@koic][])

### Bug fixes

* [#55](https://github.com/rubocop-hq/rubocop-performance/issues/55): Fix an incorrect autocorrect for `Performance/RegexpMatch` when using `str.=~(/regexp/)`. ([@koic][])
* [#108](https://github.com/rubocop-hq/rubocop-performance/pull/108): Fix an incorrect autocorrect for `Performance/ReverseEach` when there is a newline between reverse and each. ([@joe-sharp][], [@dischorde][], [@siegfault][])

### Changes
Expand Down
10 changes: 7 additions & 3 deletions lib/rubocop/cop/performance/regexp_match.rb
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,13 @@ def match_gvar?(sym)
def correct_operator(corrector, recv, arg, oper = nil)
op_range = correction_range(recv, arg)

replace_with_match_predicate_method(corrector, recv, arg, op_range)

corrector.insert_after(arg.loc.expression, ')') unless op_range.source.end_with?('(')
corrector.insert_before(recv.loc.expression, '!') if oper == :!~
end

def replace_with_match_predicate_method(corrector, recv, arg, op_range)
if TYPES_IMPLEMENTING_MATCH.include?(recv.type)
corrector.replace(op_range, '.match?(')
elsif TYPES_IMPLEMENTING_MATCH.include?(arg.type)
Expand All @@ -260,9 +267,6 @@ def correct_operator(corrector, recv, arg, oper = nil)
else
corrector.replace(op_range, '&.match?(')
end

corrector.insert_after(arg.loc.expression, ')')
corrector.insert_before(recv.loc.expression, '!') if oper == :!~
end

def swap_receiver_and_arg(corrector, recv, arg)
Expand Down
2 changes: 2 additions & 0 deletions spec/rubocop/cop/performance/regexp_match_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,8 @@ def foo
'"foo" =~ re', '"foo".match?(re)')
it_behaves_like('all legacy match methods', 'matching by =~`',
're =~ "foo"', '"foo".match?(re)')
it_behaves_like('all legacy match methods', 'matching by =~`',
're.=~("foo")', '"foo".match?(re)')
it_behaves_like('all legacy match methods', 'matching by =~`',
':foo =~ re', ':foo.match?(re)')
it_behaves_like('all legacy match methods', 'matching by =~`',
Expand Down

0 comments on commit 6d655c9

Please sign in to comment.