module RuboCop::Cop::CodeLength

Common functionality for checking length of code segments.

Constants

MSG

Private Instance Methods

build_code_length_calculator(node) click to toggle source
# File lib/rubocop/cop/mixin/code_length.rb, line 49
def build_code_length_calculator(node)
  Metrics::Utils::CodeLengthCalculator.new(
    node,
    processed_source,
    count_comments: count_comments?,
    foldable_types: count_as_one
  )
end
check_code_length(node) click to toggle source
# File lib/rubocop/cop/mixin/code_length.rb, line 31
def check_code_length(node)
  # Skip costly calculation when definitely not needed
  return if node.line_count <= max_length

  calculator = build_code_length_calculator(node)
  length = calculator.calculate
  return if length <= max_length

  location = location(node)

  add_offense(location, message: message(length, max_length)) { self.max = length }
end
count_as_one() click to toggle source
# File lib/rubocop/cop/mixin/code_length.rb, line 27
def count_as_one
  Array(cop_config['CountAsOne']).map(&:to_sym)
end
count_comments?() click to toggle source
# File lib/rubocop/cop/mixin/code_length.rb, line 23
def count_comments?
  cop_config['CountComments']
end
irrelevant_line(source_line) click to toggle source

Returns true for lines that shall not be included in the count.

# File lib/rubocop/cop/mixin/code_length.rb, line 45
def irrelevant_line(source_line)
  source_line.blank? || (!count_comments? && comment_line?(source_line))
end
location(node) click to toggle source
# File lib/rubocop/cop/mixin/code_length.rb, line 58
def location(node)
  return node.loc.name if node.casgn_type?

  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
max_length() click to toggle source
# File lib/rubocop/cop/mixin/code_length.rb, line 19
def max_length
  cop_config['Max']
end
message(length, max_length) click to toggle source
# File lib/rubocop/cop/mixin/code_length.rb, line 15
def message(length, max_length)
  format(MSG, label: cop_label, length: length, max: max_length)
end