Skip to content

Commit

Permalink
Merge pull request #49576 from fatkodima/fix-number-helper-to_d
Browse files Browse the repository at this point in the history
`NumberHelper`: handle objects responding `to_d`
  • Loading branch information
kamipo committed Oct 11, 2023
2 parents 8776e95 + fe3b07f commit e8cad01
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
Expand Up @@ -179,8 +179,10 @@ def valid_bigdecimal
case number
when Float, Rational
number.to_d(0)
else
when String
BigDecimal(number, exception: false)
else
number.to_d rescue nil
end
end
end
Expand Down
11 changes: 11 additions & 0 deletions activesupport/test/number_helper_test.rb
Expand Up @@ -15,6 +15,16 @@ class TestClassWithClassNumberHelpers
extend ActiveSupport::NumberHelper
end

class NumberWithToD
def initialize(number)
@number = number
end

def to_d
@number.to_d
end
end

def setup
@instance_with_helpers = TestClassWithInstanceNumberHelpers.new
end
Expand Down Expand Up @@ -95,6 +105,7 @@ def test_number_to_currency
assert_equal("-$,11", number_helper.number_to_currency("-,11"))
assert_equal("$0.00", number_helper.number_to_currency(-0.0))
assert_equal("$0.00", number_helper.number_to_currency("-0.0"))
assert_equal("$1.23", number_helper.number_to_currency(NumberWithToD.new(1.23)))
end
end

Expand Down

0 comments on commit e8cad01

Please sign in to comment.