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

Register offenses for variables against regexes in Performance/StringInclude #332

Merged
merged 1 commit into from
Jan 31, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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