Class: RuboCop::Cop::Performance::Squeeze
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::Performance::Squeeze
- Extended by:
- AutoCorrector
- Defined in:
- lib/rubocop/cop/performance/squeeze.rb
Overview
Identifies places where ‘gsub(/a+/, ’a’)‘ and `gsub!(/a+/, ’a’)‘ can be replaced by `squeeze(’a’)‘ and `squeeze!(’a’)‘.
The ‘squeeze(’a’)‘ method is faster than `gsub(/a+/, ’a’)‘.
Constant Summary collapse
- MSG =
'Use `%<prefer>s` instead of `%<current>s`.'
- RESTRICT_ON_SEND =
%i[gsub gsub!].freeze
- PREFERRED_METHODS =
{ gsub: :squeeze, gsub!: :squeeze! }.freeze
Instance Method Summary collapse
-
#on_send(node) ⇒ Object
(also: #on_csend)
rubocop:disable Metrics/AbcSize.
Instance Method Details
#on_send(node) ⇒ Object Also known as: on_csend
rubocop:disable Metrics/AbcSize
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/rubocop/cop/performance/squeeze.rb', line 39 def on_send(node) squeeze_candidate?(node) do |receiver, bad_method, regexp_str, replace_str| regexp_str = regexp_str[0..-2] # delete '+' from the end regexp_str = interpret_string_escapes(regexp_str) return unless replace_str == regexp_str good_method = PREFERRED_METHODS[bad_method] = format(MSG, current: bad_method, prefer: good_method) add_offense(node.loc.selector, message: ) do |corrector| string_literal = to_string_literal(replace_str) new_code = "#{receiver.source}#{node.loc.dot.source}#{good_method}(#{string_literal})" corrector.replace(node, new_code) end end end |