Skip to content

Commit

Permalink
Make Lint/NumberConversion aware of to_r
Browse files Browse the repository at this point in the history
This PR makes `Lint/NumberConversion` aware of `to_r`.
It treats `Rational` the same as` Integer`, `Float`, and `Complex`.
  • Loading branch information
koic authored and bbatsov committed Nov 6, 2021
1 parent ddc74de commit e496846
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
@@ -0,0 +1 @@
* [#10236](https://github.com/rubocop/rubocop/pull/10236): Make `Lint/NumberConversion` aware of `to_r`. ([@koic][])
7 changes: 5 additions & 2 deletions lib/rubocop/cop/lint/number_conversion.rb
Expand Up @@ -30,6 +30,7 @@ module Lint
# '10'.to_i
# '10.2'.to_f
# '10'.to_c
# '1/3'.to_r
# ['1', '2', '3'].map(&:to_i)
# foo.try(:to_f)
# bar.send(:to_c)
Expand All @@ -39,6 +40,7 @@ module Lint
# Integer('10', 10)
# Float('10.2')
# Complex('10')
# Rational('1/3')
# ['1', '2', '3'].map { |i| Integer(i, 10) }
# foo.try { |i| Float(i) }
# bar.send { |i| Complex(i) }
Expand All @@ -59,13 +61,14 @@ class NumberConversion < Base
CONVERSION_METHOD_CLASS_MAPPING = {
to_i: "#{Integer.name}(%<number_object>s, 10)",
to_f: "#{Float.name}(%<number_object>s)",
to_c: "#{Complex.name}(%<number_object>s)"
to_c: "#{Complex.name}(%<number_object>s)",
to_r: "#{Rational.name}(%<number_object>s)"
}.freeze
MSG = 'Replace unsafe number conversion with number '\
'class parsing, instead of using '\
'`%<current>s`, use stricter '\
'`%<corrected_method>s`.'
CONVERSION_METHODS = %i[Integer Float Complex to_i to_f to_c].freeze
CONVERSION_METHODS = %i[Integer Float Complex Rational to_i to_f to_c to_r].freeze
METHODS = CONVERSION_METHOD_CLASS_MAPPING.keys.map(&:inspect).join(' ')

# @!method to_method(node)
Expand Down
18 changes: 18 additions & 0 deletions spec/rubocop/cop/lint/number_conversion_spec.rb
Expand Up @@ -35,6 +35,17 @@
RUBY
end

it 'when using `#to_r`' do
expect_offense(<<~RUBY)
"1/3".to_r
^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `"1/3".to_r`, use stricter `Rational("1/3")`.
RUBY

expect_correction(<<~RUBY)
Rational("1/3")
RUBY
end

it 'when using `#to_i` for number literals' do
expect_no_offenses(<<~RUBY)
42.to_i
Expand All @@ -56,6 +67,13 @@
RUBY
end

it 'when using `#to_r` for number literals' do
expect_no_offenses(<<~RUBY)
42.to_r
42.0.to_r
RUBY
end

it 'when `#to_i` called on a variable' do
expect_offense(<<~RUBY)
string_value = '10'
Expand Down

0 comments on commit e496846

Please sign in to comment.