123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Performance::RedundantBlockCall

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/redundant_block_call.rb

Overview

Identifies the use of a &block parameter and block.call where yield would do just as well.

Examples:

# bad
def method(&block)
  block.call
end
def another(&func)
  func.call 1, 2, 3
end

# good
def method
  yield
end
def another
  yield 1, 2, 3
end

Constant Summary

Instance Method Summary

Instance Method Details

#args_include_block_pass?(blockcall) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/redundant_block_call.rb', line 99

def args_include_block_pass?(blockcall)
  _receiver, _call, *args = *blockcall

  args.any?(&:block_pass_type?)
end

#autocorrect(corrector, node) (private)

offenses are registered on the block.call nodes

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/redundant_block_call.rb', line 65

def autocorrect(corrector, node)
  _receiver, _method, *args = *node
  new_source = String.new(YIELD)
  unless args.empty?
    new_source += if parentheses?(node)
                    OPEN_PAREN
                  else
                    SPACE
                  end

    new_source << args.map(&:source).join(', ')
  end

  new_source << CLOSE_PAREN if parentheses?(node) && !args.empty?

  corrector.replace(node, new_source)
end

#calls_to_report(argname, body) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/redundant_block_call.rb', line 83

def calls_to_report(argname, body)
  return [] if blockarg_assigned?(body, argname) || shadowed_block_argument?(body, argname)

  blockarg_calls(body, argname).map do |call|
    return [] if args_include_block_pass?(call)

    call
  end
end

#on_def(node) Also known as: #on_defs

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/redundant_block_call.rb', line 47

def on_def(node)
  blockarg_def(node) do |argname, body|
    next unless body

    calls_to_report(argname, body).each do |blockcall|
      next if blockcall.block_literal?

      add_offense(blockcall, message: format(MSG, argname: argname)) do |corrector|
        autocorrect(corrector, blockcall)
      end
    end
  end
end

#on_defs(node)

Alias for #on_def.

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/redundant_block_call.rb', line 60

alias on_defs on_def

#shadowed_block_argument?(body, block_argument_of_method_signature) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/redundant_block_call.rb', line 93

def shadowed_block_argument?(body, block_argument_of_method_signature)
  return false unless body.block_type?

  body.arguments.map(&:source).include?(block_argument_of_method_signature.to_s)
end