Class: RuboCop::Cop::Performance::BindCall

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector, TargetRubyVersion
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/performance/bind_call.rb

Overview

In Ruby 2.7, ‘UnboundMethod#bind_call` has been added.

This cop identifies places where ‘bind(obj).call(args, …)` can be replaced by `bind_call(obj, args, …)`.

The ‘bind_call(obj, args, …)` method is faster than `bind(obj).call(args, …)`.

Examples:

# bad
umethod.bind(obj).call(foo, bar)
umethod.bind(obj).(foo, bar)

# good
umethod.bind_call(obj, foo, bar)

Constant Summary collapse

MSG =
'Use `bind_call(%<bind_arg>s%<comma>s%<call_args>s)` instead of `bind(%<bind_arg>s).call(%<call_args>s)`.'
RESTRICT_ON_SEND =
%i[call].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/rubocop/cop/performance/bind_call.rb', line 40

def on_send(node)
  return unless (receiver, bind_arg, call_args_node = bind_with_call_method?(node))

  range = correction_range(receiver, node)
  call_args = build_call_args(call_args_node)
  message = message(bind_arg.source, call_args)

  add_offense(range, message: message) do |corrector|
    call_args = ", #{call_args}" unless call_args.empty?

    replacement_method = "bind_call(#{bind_arg.source}#{call_args})"

    corrector.replace(range, replacement_method)
  end
end