Class: RuboCop::Cop::Performance::DoubleStartEndWith

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

Overview

This cop checks for double `#start_with?` or `#end_with?` calls separated by `||`. In some cases such calls can be replaced with an single `#start_with?`/`#end_with?` call.

`IncludeActiveSupportAliases` configuration option is used to check for `starts_with?` and `ends_with?`. These methods are defined by Active Support.

Examples:

# bad
str.start_with?("a") || str.start_with?(Some::CONST)
str.start_with?("a", "b") || str.start_with?("c")
str.end_with?(var1) || str.end_with?(var2)

# good
str.start_with?("a", Some::CONST)
str.start_with?("a", "b", "c")
str.end_with?(var1, var2)

IncludeActiveSupportAliases: false (default)

# good
str.starts_with?("a", "b") || str.starts_with?("c")
str.ends_with?(var1) || str.ends_with?(var2)

str.starts_with?("a", "b", "c")
str.ends_with?(var1, var2)

IncludeActiveSupportAliases: true

# bad
str.starts_with?("a", "b") || str.starts_with?("c")
str.ends_with?(var1) || str.ends_with?(var2)

# good
str.starts_with?("a", "b", "c")
str.ends_with?(var1, var2)

Constant Summary collapse

MSG =
'Use `%<receiver>s.%<method>s(%<combined_args>s)` ' \
'instead of `%<original_code>s`.'

Instance Method Summary collapse

Instance Method Details

#on_or(node) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rubocop/cop/performance/double_start_end_with.rb', line 47

def on_or(node)
  receiver, method, first_call_args, second_call_args = process_source(node)

  return unless receiver && second_call_args.all?(&:pure?)

  combined_args = combine_args(first_call_args, second_call_args)

  add_offense(node, message: message(node, receiver, method, combined_args)) do |corrector|
    autocorrect(corrector, first_call_args, second_call_args, combined_args)
  end
end