Class: RuboCop::Cop::Performance::EndWith

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RegexpMetacharacter
Defined in:
lib/rubocop/cop/performance/end_with.rb

Overview

Identifies unnecessary use of a regex where ‘String#end_with?` would suffice.

This cop has ‘SafeMultiline` configuration option that `true` by default because `end$` is unsafe as it will behave incompatible with `end_with?` for receiver is multiline string.

Examples:

# bad
'abc'.match?(/bc\Z/)
/bc\Z/.match?('abc')
'abc' =~ /bc\Z/
/bc\Z/ =~ 'abc'
'abc'.match(/bc\Z/)
/bc\Z/.match('abc')

# good
'abc'.end_with?('bc')

SafeMultiline: true (default)


# good
'abc'.match?(/bc$/)
/bc$/.match?('abc')
'abc' =~ /bc$/
/bc$/ =~ 'abc'
'abc'.match(/bc$/)
/bc$/.match('abc')

SafeMultiline: false


# bad
'abc'.match?(/bc$/)
/bc$/.match?('abc')
'abc' =~ /bc$/
/bc$/ =~ 'abc'
'abc'.match(/bc$/)
/bc$/.match('abc')

Constant Summary collapse

MSG =
'Use `String#end_with?` instead of a regex match anchored to the end of the string.'
RESTRICT_ON_SEND =
%i[match =~ match?].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object Also known as: on_csend, on_match_with_lvasgn



63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/rubocop/cop/performance/end_with.rb', line 63

def on_send(node)
  return unless (receiver, regex_str = redundant_regex?(node))

  add_offense(node) do |corrector|
    receiver, regex_str = regex_str, receiver if receiver.is_a?(String)
    regex_str = drop_end_metacharacter(regex_str)
    regex_str = interpret_string_escapes(regex_str)
    dot = node.loc.dot ? node.loc.dot.source : '.'

    new_source = "#{receiver.source}#{dot}end_with?(#{to_string_literal(regex_str)})"

    corrector.replace(node, new_source)
  end
end