class RuboCop::Cop::Metrics::BlockNesting

Checks for excessive nesting of conditional and looping constructs.

You can configure if blocks are considered using the `CountBlocks` option. When set to `false` (the default) blocks are not counted towards the nesting level. Set to `true` to count blocks as well.

The maximum level of nesting allowed is configurable.

Constants

NESTING_BLOCKS

Public Instance Methods

on_new_investigation() click to toggle source
# File lib/rubocop/cop/metrics/block_nesting.rb, line 19
def on_new_investigation
  return if processed_source.blank?

  max = cop_config['Max']
  check_nesting_level(processed_source.ast, max, 0)
end

Private Instance Methods

check_nesting_level(node, max, current_level) click to toggle source
# File lib/rubocop/cop/metrics/block_nesting.rb, line 28
def check_nesting_level(node, max, current_level)
  if consider_node?(node)
    current_level += 1 unless node.if_type? && node.elsif?
    if current_level > max
      self.max = current_level
      unless part_of_ignored_node?(node)
        add_offense(node, message: message(max)) { ignore_node(node) }
      end
    end
  end

  node.each_child_node do |child_node|
    check_nesting_level(child_node, max, current_level)
  end
end
consider_node?(node) click to toggle source
# File lib/rubocop/cop/metrics/block_nesting.rb, line 44
def consider_node?(node)
  return true if NESTING_BLOCKS.include?(node.type)

  count_blocks? && node.block_type?
end
count_blocks?() click to toggle source
# File lib/rubocop/cop/metrics/block_nesting.rb, line 54
def count_blocks?
  cop_config['CountBlocks']
end
message(max) click to toggle source
# File lib/rubocop/cop/metrics/block_nesting.rb, line 50
def message(max)
  "Avoid more than #{max} levels of block nesting."
end