diff --git a/CHANGELOG.md b/CHANGELOG.md index 41db0807bd..8ccbe0e790 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## master (unreleased) +### Bug fixes + +* [#150](https://github.com/rubocop-hq/rubocop-performance/pull/150): Fix an incorrect autocorrect for `Performance/BigDecimalWithNumericArgument` when a precision is specified. ([@eugeneius][]) + ## 1.7.0 (2020-07-07) ### New features diff --git a/lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb b/lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb index 64aaf91bec..def0968dc5 100644 --- a/lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb +++ b/lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb @@ -25,6 +25,8 @@ class BigDecimalWithNumericArgument < Cop def on_send(node) big_decimal_with_numeric_argument?(node) do |numeric| + next if numeric.float_type? && specifies_precision?(node) + add_offense(node, location: numeric.source_range) end end @@ -36,6 +38,12 @@ def autocorrect(node) end end end + + private + + def specifies_precision?(node) + node.arguments.size > 1 && !node.arguments[1].hash_type? + end end end end diff --git a/spec/rubocop/cop/performance/big_decimal_with_numeric_argument_spec.rb b/spec/rubocop/cop/performance/big_decimal_with_numeric_argument_spec.rb index 919bb01382..b0e0a45119 100644 --- a/spec/rubocop/cop/performance/big_decimal_with_numeric_argument_spec.rb +++ b/spec/rubocop/cop/performance/big_decimal_with_numeric_argument_spec.rb @@ -16,12 +16,31 @@ it 'registers an offense and corrects when using `BigDecimal` with float' do expect_offense(<<~RUBY) - BigDecimal(1.5, 2, exception: true) + BigDecimal(1.5, exception: true) ^^^ Convert numeric argument to string before passing to `BigDecimal`. RUBY expect_correction(<<~RUBY) - BigDecimal('1.5', 2, exception: true) + BigDecimal('1.5', exception: true) + RUBY + end + + it 'does not register an offense when using `BigDecimal` with float and precision' do + expect_no_offenses(<<~RUBY) + BigDecimal(3.14, 1) + RUBY + end + + it 'does not register an offense when using `BigDecimal` with float and non-literal precision' do + expect_no_offenses(<<~RUBY) + precision = 1 + BigDecimal(3.14, precision) + RUBY + end + + it 'does not register an offense when using `BigDecimal` with float, precision, and a keyword argument' do + expect_no_offenses(<<~RUBY) + BigDecimal(3.14, 1, exception: true) RUBY end