Skip to content

Commit c2c623e

Browse files
authored
Merge pull request #332 from fatkodima/string-include-variables
Register offenses for variables against regexes in `Performance/StringInclude`
2 parents 8fafbe4 + 357f6dc commit c2c623e

File tree

3 files changed

+15
-14
lines changed

3 files changed

+15
-14
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#332](https://github.com/rubocop/rubocop-performance/pull/332): Register offenses for variables against regexes in `Performance/StringInclude`. ([@fatkodima][])

lib/rubocop/cop/performance/string_include.rb

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,19 @@ module Performance
66
# Identifies unnecessary use of a regex where `String#include?` would suffice.
77
#
88
# @safety
9-
# This cop's offenses are not safe to autocorrect if a receiver is nil.
9+
# This cop's offenses are not safe to autocorrect if a receiver is nil or a Symbol.
1010
#
1111
# @example
1212
# # bad
13-
# 'abc'.match?(/ab/)
14-
# /ab/.match?('abc')
15-
# 'abc' =~ /ab/
16-
# /ab/ =~ 'abc'
17-
# 'abc'.match(/ab/)
18-
# /ab/.match('abc')
13+
# str.match?(/ab/)
14+
# /ab/.match?(str)
15+
# str =~ /ab/
16+
# /ab/ =~ str
17+
# str.match(/ab/)
18+
# /ab/.match(str)
1919
#
2020
# # good
21-
# 'abc'.include?('ab')
21+
# str.include?('ab')
2222
class StringInclude < Base
2323
extend AutoCorrector
2424

@@ -27,7 +27,7 @@ class StringInclude < Base
2727

2828
def_node_matcher :redundant_regex?, <<~PATTERN
2929
{(send $!nil? {:match :=~ :!~ :match?} (regexp (str $#literal?) (regopt)))
30-
(send (regexp (str $#literal?) (regopt)) {:match :match?} $str)
30+
(send (regexp (str $#literal?) (regopt)) {:match :match?} $_)
3131
(match-with-lvasgn (regexp (str $#literal?) (regopt)) $_)}
3232
PATTERN
3333

spec/rubocop/cop/performance/string_include_spec.rb

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -151,11 +151,11 @@
151151
expect_no_offenses('expect(subject.spin).to match(/\A\n/)')
152152
end
153153

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

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

0 commit comments

Comments
 (0)