class RuboCop::Cop::Performance::RedundantBlockCall

This cop identifies the use of a `&block` parameter and `block.call` where `yield` would do just as well.

@example

# 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

Constants

CLOSE_PAREN
MSG
OPEN_PAREN
SPACE
YIELD

Public Instance Methods

on_def(node) click to toggle source
# 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|
      add_offense(blockcall, message: format(MSG, argname: argname)) do |corrector|
        autocorrect(corrector, blockcall)
      end
    end
  end
end

Private Instance Methods

args_include_block_pass?(blockcall) click to toggle source
# File lib/rubocop/cop/performance/redundant_block_call.rb, line 96
def args_include_block_pass?(blockcall)
  _receiver, _call, *args = *blockcall

  args.any?(&:block_pass_type?)
end
autocorrect(corrector, node) click to toggle source

offenses are registered on the `block.call` nodes

# File lib/rubocop/cop/performance/redundant_block_call.rb, line 62
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.source_range, new_source)
end
calls_to_report(argname, body) click to toggle source
# File lib/rubocop/cop/performance/redundant_block_call.rb, line 80
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
shadowed_block_argument?(body, block_argument_of_method_signature) click to toggle source
# File lib/rubocop/cop/performance/redundant_block_call.rb, line 90
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