Class: RuboCop::Cop::Performance::StringInclude
Relationships & Source Files | |
Super Chains via Extension / Inclusion / Inheritance | |
Class Chain:
self,
AutoCorrector,
Base
|
|
Instance Chain:
self,
Base
|
|
Inherits: |
Base
|
Defined in: | lib/rubocop/cop/performance/string_include.rb |
Overview
Identifies unnecessary use of a regex where String#include?
would suffice.
Constant Summary
-
MSG =
# File 'lib/rubocop/cop/performance/string_include.rb', line 26'Use `%<negation>sString#include?` instead of a regex match with literal-only pattern.'
-
RESTRICT_ON_SEND =
# File 'lib/rubocop/cop/performance/string_include.rb', line 27%i[match =~ !~ match? ===].freeze
Instance Method Summary
-
#on_csend(node)
Alias for #on_send.
-
#on_match_with_lvasgn(node)
Alias for #on_send.
- #on_send(node) (also: #on_csend, #on_match_with_lvasgn)
- #literal?(regex_str) ⇒ Boolean private
Instance Method Details
#literal?(regex_str) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/performance/string_include.rb', line 59
def literal?(regex_str) regex_str.match?(/\A#{Util::LITERAL_REGEX}+\z/o) end
#on_csend(node)
Alias for #on_send.
# File 'lib/rubocop/cop/performance/string_include.rb', line 54
alias on_csend on_send
#on_match_with_lvasgn(node)
Alias for #on_send.
# File 'lib/rubocop/cop/performance/string_include.rb', line 55
alias on_match_with_lvasgn on_send
#on_send(node) Also known as: #on_csend, #on_match_with_lvasgn
[ GitHub ]# File 'lib/rubocop/cop/performance/string_include.rb', line 37
def on_send(node) return unless (receiver, regex_str = redundant_regex?(node)) negation = node.send_type? && node.method?(:!~) = format(MSG, negation: ('!' if negation)) add_offense(node, message: ) do |corrector| receiver, regex_str = regex_str, receiver if receiver.is_a?(String) regex_str = interpret_string_escapes(regex_str) dot = node.loc.dot ? node.loc.dot.source : '.' new_source = "#{'!' if negation}#{receiver.source}#{dot}include?(#{to_string_literal(regex_str)})" corrector.replace(node, new_source) end end