Skip to content

Commit

Permalink
Enhance Performance/StringInclude to handle === method
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima committed Nov 28, 2023
1 parent c5bc8f4 commit c584a27
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
1 change: 1 addition & 0 deletions changelog/change_string_include_to_handle_===.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#395](https://github.com/rubocop/rubocop-performance/issues/395): Enhance `Performance/StringInclude` to handle `===` method. ([@fatkodima][])
5 changes: 3 additions & 2 deletions lib/rubocop/cop/performance/string_include.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,19 @@ module Performance
# /ab/ =~ str
# str.match(/ab/)
# /ab/.match(str)
# /ab/ === str
#
# # good
# str.include?('ab')
class StringInclude < Base
extend AutoCorrector

MSG = 'Use `%<negation>sString#include?` instead of a regex match with literal-only pattern.'
RESTRICT_ON_SEND = %i[match =~ !~ match?].freeze
RESTRICT_ON_SEND = %i[match =~ !~ match? ===].freeze

def_node_matcher :redundant_regex?, <<~PATTERN
{(call $!nil? {:match :=~ :!~ :match?} (regexp (str $#literal?) (regopt)))
(send (regexp (str $#literal?) (regopt)) {:match :match?} $_)
(send (regexp (str $#literal?) (regopt)) {:match :match? :===} $_)
(match-with-lvasgn (regexp (str $#literal?) (regopt)) $_)}
PATTERN

Expand Down
23 changes: 23 additions & 0 deletions spec/rubocop/cop/performance/string_include_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,29 @@
include_examples('different match methods', ' =~')
include_examples('different match methods', '.match')

it 'registers an offense and corrects /abc/ === str' do
expect_offense(<<~RUBY)
/abc/ === 'str'
^^^^^^^^^^^^^^^ Use `String#include?` instead of a regex match with literal-only pattern.
RUBY

expect_correction(<<~RUBY)
'str'.include?('abc')
RUBY
end

it 'does not register an offense for str === /abc/' do
expect_no_offenses(<<~RUBY)
str === /abc/
RUBY
end

it 'does not register an offense when receiver of `===` is not a simple regexp' do
expect_no_offenses(<<~RUBY)
/abc[de]/ === str
RUBY
end

it 'allows match without a receiver' do
expect_no_offenses('expect(subject.spin).to match(/\A\n/)')
end
Expand Down

0 comments on commit c584a27

Please sign in to comment.