Skip to content

Commit

Permalink
Register offenses for variables against regexes in `Performance/Strin…
Browse files Browse the repository at this point in the history
…gInclude`
  • Loading branch information
fatkodima committed Jan 7, 2023
1 parent a1e0556 commit 357f6dc
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 14 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#332](https://github.com/rubocop/rubocop-performance/pull/332): Register offenses for variables against regexes in `Performance/StringInclude`. ([@fatkodima][])
18 changes: 9 additions & 9 deletions lib/rubocop/cop/performance/string_include.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,19 @@ module Performance
# Identifies unnecessary use of a regex where `String#include?` would suffice.
#
# @safety
# This cop's offenses are not safe to autocorrect if a receiver is nil.
# This cop's offenses are not safe to autocorrect if a receiver is nil or a Symbol.
#
# @example
# # bad
# 'abc'.match?(/ab/)
# /ab/.match?('abc')
# 'abc' =~ /ab/
# /ab/ =~ 'abc'
# 'abc'.match(/ab/)
# /ab/.match('abc')
# str.match?(/ab/)
# /ab/.match?(str)
# str =~ /ab/
# /ab/ =~ str
# str.match(/ab/)
# /ab/.match(str)
#
# # good
# 'abc'.include?('ab')
# str.include?('ab')
class StringInclude < Base
extend AutoCorrector

Expand All @@ -27,7 +27,7 @@ class StringInclude < Base

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

Expand Down
10 changes: 5 additions & 5 deletions spec/rubocop/cop/performance/string_include_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -151,11 +151,11 @@
expect_no_offenses('expect(subject.spin).to match(/\A\n/)')
end

# Symbol object does not have `include?` method.
# A variable possible to be a symbol object, so if `match?` argument is
# a variable, accept it.
it 'allows argument of `match?` is not a string literal' do
expect_no_offenses('/ /.match?(content_as_symbol)')
it 'registers an offense and corrects when argument of `match?` is not a string literal' do
expect_offense(<<~RUBY)
/ /.match?(content)
^^^^^^^^^^^^^^^^^^^ Use `String#include?` instead of a regex match with literal-only pattern.
RUBY
end

it 'registers an offense and corrects when using `!~`' do
Expand Down

0 comments on commit 357f6dc

Please sign in to comment.