Skip to content

Commit

Permalink
NumberHelper: handle objects responding to_d
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima committed Oct 10, 2023
1 parent c8149e6 commit fe3b07f
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 @@ -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 fe3b07f

Please sign in to comment.