class RuboCop::Cop::Lint::NumberConversion

This cop warns the usage of unsafe number conversions. Unsafe number conversion can cause unexpected error if auto type conversion fails. Cop prefer parsing with number class instead.

@example

# bad

'10'.to_i
'10.2'.to_f
'10'.to_c

# good

Integer('10', 10)
Float('10.2')
Complex('10')

Constants

CONVERSION_METHOD_CLASS_MAPPING
MSG

Public Instance Methods

autocorrect(node) click to toggle source
# File lib/rubocop/cop/lint/number_conversion.rb, line 56
def autocorrect(node)
  lambda do |corrector|
    corrector.replace(node.loc.expression,
                      correct_method(node, node.receiver))
  end
end
on_send(node) click to toggle source
# File lib/rubocop/cop/lint/number_conversion.rb, line 42
def on_send(node)
  to_method(node) do |receiver, to_method|
    next if date_time_object?(receiver)

    message = format(
      MSG,
      number_object: receiver.source,
      to_method: to_method,
      corrected_method: correct_method(node, receiver)
    )
    add_offense(node, message: message)
  end
end

Private Instance Methods

correct_method(node, receiver) click to toggle source
# File lib/rubocop/cop/lint/number_conversion.rb, line 74
def correct_method(node, receiver)
  format(CONVERSION_METHOD_CLASS_MAPPING[node.method_name],
         number_object: receiver.source)
end
date_time_object?(node) click to toggle source
# File lib/rubocop/cop/lint/number_conversion.rb, line 65
def date_time_object?(node)
  child = node
  while child&.send_type?
    return true if datetime? child

    child = child.children[0]
  end
end