Class: RuboCop::Cop::Performance::Squeeze
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/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
-
MSG =
# File 'lib/rubocop/cop/performance/squeeze.rb', line 24'Use `%<prefer>s` instead of `%<current>s`.'
-
PREFERRED_METHODS =
# File 'lib/rubocop/cop/performance/squeeze.rb', line 27{ gsub: :squeeze, gsub!: :squeeze! }.freeze
-
RESTRICT_ON_SEND =
# File 'lib/rubocop/cop/performance/squeeze.rb', line 25%i[gsub gsub!].freeze
Instance Method Summary
-
#on_csend(node)
Alias for #on_send.
- #on_send(node) (also: #on_csend)
- #repeating_literal?(regex_str) ⇒ Boolean private
Instance Method Details
#on_csend(node)
Alias for #on_send.
# File 'lib/rubocop/cop/performance/squeeze.rb', line 61
alias on_csend on_send
#on_send(node) Also known as: #on_csend
[ GitHub ]# 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| # FIXME: When requiring only RuboCop 1.70.0 and above, # `dup` in `replace_str.dup` becomes unnecessary, as # frozen strings are handled in the `to_string_literal` # implementation. Please remove it. string_literal = to_string_literal(replace_str.dup) new_code = "#{receiver.source}#{node.loc.dot.source}#{good_method}(#{string_literal})" corrector.replace(node, new_code) end end end
#repeating_literal?(regex_str) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/performance/squeeze.rb', line 65
def repeating_literal?(regex_str) regex_str.match?(/\A(?:#{Util::LITERAL_REGEX})\+\z/o) end