class RuboCop::Cop::Performance::DoubleStartEndWith
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.
@example
@bad str.start_with?("a") || str.start_with?(Some::CONST) str.start_with?("a", "b") || str.start_with?("c") var1 = ... var2 = ... str.end_with?(var1) || str.end_with?(var2) @good str.start_with?("a", Some::CONST) str.start_with?("a", "b", "c") var1 = ... var2 = ... str.end_with?(var1, var2)
Constants
- MSG
Public Instance Methods
autocorrect(node)
click to toggle source
# File lib/rubocop/cop/performance/double_start_end_with.rb, line 41 def autocorrect(node) _receiver, _method, first_call_args, second_call_args = process_source(node) combined_args = combine_args(first_call_args, second_call_args) first_argument = first_call_args.first.loc.expression last_argument = second_call_args.last.loc.expression range = first_argument.join(last_argument) lambda do |corrector| corrector.replace(range, combined_args) end end
on_or(node)
click to toggle source
# File lib/rubocop/cop/performance/double_start_end_with.rb, line 28 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_for_double_call(node, receiver, method, combined_args) end
Private Instance Methods
add_offense_for_double_call(node, receiver, method, combined_args)
click to toggle source
# File lib/rubocop/cop/performance/double_start_end_with.rb, line 69 def add_offense_for_double_call(node, receiver, method, combined_args) msg = format(MSG, receiver: receiver.source, method: method, combined_args: combined_args, original_code: node.source) add_offense(node, message: msg) end
check_for_active_support_aliases?()
click to toggle source
# File lib/rubocop/cop/performance/double_start_end_with.rb, line 78 def check_for_active_support_aliases? cop_config['IncludeActiveSupportAliases'] end
combine_args(first_call_args, second_call_args)
click to toggle source
# File lib/rubocop/cop/performance/double_start_end_with.rb, line 65 def combine_args(first_call_args, second_call_args) (first_call_args + second_call_args).map(&:source).join(', ') end
process_source(node)
click to toggle source
# File lib/rubocop/cop/performance/double_start_end_with.rb, line 57 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