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.

NOTE: This cop produces code with significantly worse performance when a block is being passed to the method and as such should not be enabled.

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



54
55
56
# File 'lib/rubocop/cop/performance/block_given_with_explicit_block.rb', line 54

def self.autocorrect_incompatible_with
  [Lint::UnusedMethodArgument]
end

Instance Method Details

#on_send(node) ⇒ Object



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

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