From fe3b07f6836a7a48447a2906704adb330237187e Mon Sep 17 00:00:00 2001 From: fatkodima Date: Wed, 11 Oct 2023 01:38:21 +0300 Subject: [PATCH] `NumberHelper`: handle objects responding `to_d` --- .../active_support/number_helper/number_converter.rb | 4 +++- activesupport/test/number_helper_test.rb | 11 +++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/number_helper/number_converter.rb b/activesupport/lib/active_support/number_helper/number_converter.rb index 22b4a936d1d..fdcced24d9f 100644 --- a/activesupport/lib/active_support/number_helper/number_converter.rb +++ b/activesupport/lib/active_support/number_helper/number_converter.rb @@ -179,8 +179,10 @@ module ActiveSupport 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 diff --git a/activesupport/test/number_helper_test.rb b/activesupport/test/number_helper_test.rb index 37272ee19d7..a1633ba87b2 100644 --- a/activesupport/test/number_helper_test.rb +++ b/activesupport/test/number_helper_test.rb @@ -15,6 +15,16 @@ module ActiveSupport 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 @@ -95,6 +105,7 @@ module ActiveSupport 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