class RuboCop::Cop::Style::NumericLiterals

This cop checks for big numeric literals without _ between groups of digits in them.

Constants

MSG

Public Instance Methods

on_float(node) click to toggle source
# File lib/rubocop/cop/style/numeric_literals.rb, line 21
def on_float(node)
  check(node)
end
on_int(node) click to toggle source
# File lib/rubocop/cop/style/numeric_literals.rb, line 17
def on_int(node)
  check(node)
end

Private Instance Methods

autocorrect(node) click to toggle source
# File lib/rubocop/cop/style/numeric_literals.rb, line 48
def autocorrect(node)
  lambda do |corrector|
    corrector.replace(node.source_range, format_number(node))
  end
end
check(node) click to toggle source
# File lib/rubocop/cop/style/numeric_literals.rb, line 31
def check(node)
  int = integer_part(node)

  # TODO: handle non-decimal literals as well
  return if int.start_with?('0')
  return unless int.size >= min_digits

  case int
  when /^\d+$/
    add_offense(node, :expression) { self.max = int.size + 1 }
  when /\d{4}/, /_\d{1,2}_/
    add_offense(node, :expression) do
      self.config_to_allow_offenses = { 'Enabled' => false }
    end
  end
end
format_number(node) click to toggle source
# File lib/rubocop/cop/style/numeric_literals.rb, line 54
def format_number(node)
  int_part, float_part = node.source.split('.')
  int_part = int_part.to_i
  formatted_int = int_part
                  .abs
                  .to_s
                  .reverse
                  .gsub(/...(?=.)/, '\&_')
                  .reverse
  formatted_int.insert(0, '-') if int_part < 0

  if float_part
    format('%s.%s', formatted_int, float_part)
  else
    formatted_int
  end
end
integer_part(node) click to toggle source
# File lib/rubocop/cop/style/numeric_literals.rb, line 72
def integer_part(node)
  node.source.sub(/^[+-]/, '').split('.').first
end
min_digits() click to toggle source
# File lib/rubocop/cop/style/numeric_literals.rb, line 76
def min_digits
  cop_config['MinDigits']
end
parameter_name() click to toggle source
# File lib/rubocop/cop/style/numeric_literals.rb, line 27
def parameter_name
  'MinDigits'
end