123456789_123456789_123456789_123456789_123456789_

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

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, AutoCorrector, Base
Instance Chain:
self, Base
Inherits: Base
  • Object
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

Class Method Summary

Instance Method Summary

Class Method Details

.autocorrect_incompatible_with

[ GitHub ]

  
# 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)

[ GitHub ]

  
# 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