Class: RuboCop::Cop::Performance::Caller

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

Overview

Identifies places where ‘caller` can be replaced by `caller(n..n).first`.

Examples:

# bad
caller[1]
caller.first
caller_locations[1]
caller_locations.first

# good
caller(2..2).first
caller(1..1).first
caller_locations(2..2).first
caller_locations(1..1).first

Constant Summary collapse

MSG =
'Use `%<preferred_method>s` instead of `%<current_method>s`.'
RESTRICT_ON_SEND =
%i[first []].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
55
56
57
# File 'lib/rubocop/cop/performance/caller.rb', line 40

def on_send(node)
  return unless caller_with_scope_method?(node)

  method_name = node.receiver.method_name
  caller_arg = node.receiver.first_argument
  n = caller_arg ? int_value(caller_arg) : 1
  if node.method?(:[])
    m = int_value(node.first_argument)
    n += m
  end

  preferred_method = "#{method_name}(#{n}..#{n}).first"

  message = format(MSG, preferred_method: preferred_method, current_method: node.source)
  add_offense(node, message: message) do |corrector|
    corrector.replace(node, preferred_method)
  end
end