module RuboCop::Cop::MethodComplexity

@api private

This module handles measurement and reporting of complexity in methods.

Public Instance Methods

on_block(node) click to toggle source
# File lib/rubocop/cop/mixin/method_complexity.rb, line 24
def on_block(node)
  define_method?(node) do |name|
    return if allowed_method?(name) || matches_allowed_pattern?(name)

    check_complexity(node, name)
  end
end
Also aliased as: on_numblock
on_def(node) click to toggle source
# File lib/rubocop/cop/mixin/method_complexity.rb, line 17
def on_def(node)
  return if allowed_method?(node.method_name) || matches_allowed_pattern?(node.method_name)

  check_complexity(node, node.method_name)
end
Also aliased as: on_defs
on_defs(node)
Alias for: on_def
on_numblock(node)
Alias for: on_block

Private Instance Methods

check_complexity(node, method_name) click to toggle source
# File lib/rubocop/cop/mixin/method_complexity.rb, line 42
def check_complexity(node, method_name)
  # Accepts empty methods always.
  return unless node.body

  max = cop_config['Max']
  reset_repeated_csend
  complexity, abc_vector = complexity(node.body)

  return unless complexity > max

  msg = format(
    self.class::MSG,
    method: method_name, complexity: complexity, abc_vector: abc_vector, max: max
  )
  location = location(node)

  add_offense(location, message: msg) { self.max = complexity.ceil }
end
complexity(body) click to toggle source
# File lib/rubocop/cop/mixin/method_complexity.rb, line 61
def complexity(body)
  score = 1
  body.each_node(:lvasgn, *self.class::COUNTED_NODES) do |node|
    if node.lvasgn_type?
      reset_on_lvasgn(node)
    else
      score += complexity_score_for(node)
    end
  end
  score
end
location(node) click to toggle source
# File lib/rubocop/cop/mixin/method_complexity.rb, line 73
def location(node)
  if LSP.enabled?
    end_range = node.loc.respond_to?(:name) ? node.loc.name : node.loc.begin
    node.source_range.begin.join(end_range)
  else
    node.source_range
  end
end