Class: RuboCop::Cop::Performance::BlockGivenWithExplicitBlock

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

Overview

Identifies unnecessary use of a ‘block_given?` where explicit check of block argument would suffice.

Examples:

# bad
def method(&block)
  do_something if block_given?
end

# good
def method(&block)
  do_something if block
end

# good - block is reassigned
def method(&block)
  block ||= -> { do_something }
  warn "Using default ..." unless block_given?
  # ...
end

Constant Summary collapse

RESTRICT_ON_SEND =
%i[block_given?].freeze
MSG =
'Check block argument explicitly instead of using `block_given?`.'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.autocorrect_incompatible_withObject



51
52
53
# File 'lib/rubocop/cop/performance/block_given_with_explicit_block.rb', line 51

def self.autocorrect_incompatible_with
  [Lint::UnusedMethodArgument]
end

Instance Method Details

#on_send(node) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rubocop/cop/performance/block_given_with_explicit_block.rb', line 35

def on_send(node)
  def_node = node.each_ancestor(:def, :defs).first
  return unless def_node

  block_arg = def_node.arguments.find(&:blockarg_type?)
  return unless block_arg
  return unless (block_arg_name = block_arg.loc.name)

  block_arg_name = block_arg_name.source.to_sym
  return if reassigns_block_arg?(def_node, block_arg_name)

  add_offense(node) do |corrector|
    corrector.replace(node, block_arg_name)
  end
end