lib/rubocop/cop/performance/start_with.rb in rubocop-performance-1.5.0 vs lib/rubocop/cop/performance/start_with.rb in rubocop-performance-1.5.1

- old
+ new

@@ -7,23 +7,27 @@ # `String#start_with?` would suffice. # # @example # # bad # 'abc'.match?(/\Aab/) + # /\Aab/.match?('abc') # 'abc' =~ /\Aab/ + # /\Aab/ =~ 'abc' # 'abc'.match(/\Aab/) + # /\Aab/.match('abc') # # # good # 'abc'.start_with?('ab') class StartWith < Cop MSG = 'Use `String#start_with?` instead of a regex match anchored to ' \ 'the beginning of the string.' SINGLE_QUOTE = "'" def_node_matcher :redundant_regex?, <<-PATTERN {(send $!nil? {:match :=~ :match?} (regexp (str $#literal_at_start?) (regopt))) - (send (regexp (str $#literal_at_start?) (regopt)) {:match :=~} $_)} + (send (regexp (str $#literal_at_start?) (regopt)) {:match :match?} $_) + (match-with-lvasgn (regexp (str $#literal_at_start?) (regopt)) $_)} PATTERN def literal_at_start?(regex_str) # is this regexp 'literal' in the sense of only matching literal # chars, rather than using metachars like `.` and `*` and so on? @@ -37,9 +41,10 @@ def on_send(node) return unless redundant_regex?(node) add_offense(node) end + alias on_match_with_lvasgn on_send def autocorrect(node) redundant_regex?(node) do |receiver, regex_str| receiver, regex_str = regex_str, receiver if receiver.is_a?(String) regex_str = regex_str[2..-1] # drop \A anchor