Class: RuboCop::Cop::Performance::DeleteSuffix
Relationships & Source Files | |
Super Chains via Extension / Inclusion / Inheritance | |
Class Chain:
self,
TargetRubyVersion,
AutoCorrector,
Base
|
|
Instance Chain:
self,
::RuboCop::Cop::RegexpMetacharacter ,
Base
|
|
Inherits: |
Base
|
Defined in: | lib/rubocop/cop/performance/delete_suffix.rb |
Overview
In Ruby 2.5, String#delete_suffix
has been added.
This cop identifies places where gsub(/suffix\z/, '')
and sub(/suffix\z/, '')
can be replaced by delete_suffix('suffix')
.
This cop has SafeMultiline
configuration option that true
by default because
suffix$
is unsafe as it will behave incompatible with delete_suffix?
for receiver is multiline string.
The delete_suffix('suffix')
method is faster than gsub(/suffix\z/, '')
.
Constant Summary
-
MSG =
# File 'lib/rubocop/cop/performance/delete_suffix.rb', line 56'Use `%<prefer>s` instead of `%<current>s`.'
-
PREFERRED_METHODS =
# File 'lib/rubocop/cop/performance/delete_suffix.rb', line 59{ gsub: :delete_suffix, gsub!: :delete_suffix!, sub: :delete_suffix, sub!: :delete_suffix! }.freeze
-
RESTRICT_ON_SEND =
# File 'lib/rubocop/cop/performance/delete_suffix.rb', line 57%i[gsub gsub! sub sub!].freeze
Instance Attribute Summary
Instance Method Summary
-
#on_csend(node)
Alias for #on_send.
- #on_send(node) (also: #on_csend)
::RuboCop::Cop::RegexpMetacharacter
- Included
Instance Method Details
#on_csend(node)
Alias for #on_send.
# File 'lib/rubocop/cop/performance/delete_suffix.rb', line 90
alias on_csend on_send
#on_send(node) Also known as: #on_csend
[ GitHub ]# File 'lib/rubocop/cop/performance/delete_suffix.rb', line 71
def on_send(node) return unless (receiver, bad_method, regexp_str, replace_string = delete_suffix_candidate?(node)) return unless replace_string.empty? good_method = PREFERRED_METHODS[bad_method] = format(MSG, current: bad_method, prefer: good_method) add_offense(node.loc.selector, message: ) do |corrector| regexp_str = (regexp_str) regexp_str = interpret_string_escapes(regexp_str) string_literal = to_string_literal(regexp_str) new_code = "#{receiver.source}#{node.loc.dot.source}#{good_method}(#{string_literal})" corrector.replace(node, new_code) end end