class RuboCop::Cop::Style::NumericLiterals
of digits in them.
This cop checks for big numeric literals without _ between groups
def autocorrect(node)
def autocorrect(node) @corrections << lambda do |corrector| corrector.replace( node.loc.expression, format_number(node) ) end end
def check(node)
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
def format_number(node)
def format_number(node) int_part, float_part = node.loc.expression.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
def integer_part(node)
def integer_part(node) node.loc.expression.source.sub(/^[+-]/, '').split('.').first end
def min_digits
def min_digits cop_config['MinDigits'] end
def on_float(node)
def on_float(node) check(node) end
def on_int(node)
def on_int(node) check(node) end
def parameter_name
def parameter_name 'MinDigits' end