Skip to content

Commit

Permalink
Merge pull request rails#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
1 parent 2874def commit 72656c5
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 @@ -91,6 +101,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 72656c5

Please sign in to comment.