class RuboCop::Cop::Performance::DoubleStartEndWith
str.ends_with?(var1, var2)
str.starts_with?(“a”, “b”, “c”)
# good
str.ends_with?(var1) || str.ends_with?(var2)
str.starts_with?(“a”, “b”) || str.starts_with?(“c”)
# bad
@example IncludeActiveSupportAliases: true
str.ends_with?(var1, var2)
str.starts_with?(“a”, “b”, “c”)
str.ends_with?(var1) || str.ends_with?(var2)
str.starts_with?(“a”, “b”) || str.starts_with?(“c”)
# good
@example IncludeActiveSupportAliases: false (default)
str.end_with?(var1, var2)
str.start_with?(“a”, “b”, “c”)
str.start_with?(“a”, Some::CONST)
# good
str.end_with?(var1) || str.end_with?(var2)
str.start_with?(“a”, “b”) || str.start_with?(“c”)
str.start_with?(“a”) || str.start_with?(Some::CONST)
# bad
@example
`starts_with?‘ and `ends_with?`. These methods are defined by Active Support.
`IncludeActiveSupportAliases` configuration option is used to check for
with an single `#start_with?`/`#end_with?` call.
separated by `||`. In some cases such calls can be replaced
Checks for double `#start_with?` or `#end_with?` calls
def autocorrect(corrector, first_call_args, second_call_args, combined_args)
def autocorrect(corrector, first_call_args, second_call_args, combined_args) first_argument = first_call_args.first.source_range last_argument = second_call_args.last.source_range range = first_argument.join(last_argument) corrector.replace(range, combined_args) end
def check_for_active_support_aliases?
def check_for_active_support_aliases? cop_config['IncludeActiveSupportAliases'] end
def combine_args(first_call_args, second_call_args)
def combine_args(first_call_args, second_call_args) (first_call_args + second_call_args).map(&:source).join(', ') end
def message(node, receiver, first_call_args, method, combined_args)
def message(node, receiver, first_call_args, method, combined_args) dot = first_call_args.first.parent.send_type? ? '.' : '&.' replacement = "#{receiver.source}#{dot}#{method}(#{combined_args})" format(MSG, replacement: replacement, original_code: node.source) end
def on_or(node)
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, first_call_args, method, combined_args)) do |corrector| autocorrect(corrector, first_call_args, second_call_args, combined_args) end end
def process_source(node)
def process_source(node) if check_for_active_support_aliases? check_with_active_support_aliases(node) else two_start_end_with_calls(node) end end