Skip to content

Commit 53b07fd

Browse files
committed
[GR-20121] BigDecimal coerce initial argument using to_str (#1826).
PullRequest: truffleruby/1193
2 parents b78f6bb + 990b6e6 commit 53b07fd

File tree

3 files changed

+51
-2
lines changed

3 files changed

+51
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ Bug fixes:
4040
* Fixed File.fnmatch causes ArrayIndexOutOfBoundsException (#1845).
4141
* Make `String#concat` work with no or multiple arguments (#1519).
4242
* Make `Array#concat` work with no or multiple arguments (#1519).
43+
* Fixed BigDecimal coerce initial argument using `to_str` (#1826).
4344

4445
Compatibility:
4546

lib/truffle/bigdecimal.rb

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -326,8 +326,50 @@ def self.new(*args)
326326
end
327327

328328
module Kernel
329-
def BigDecimal(value, precision = Truffle::UNDEFINED)
330-
TrufflePrimitive.bigdecimal_new value, precision, true
329+
def BigDecimal(value, precision = Truffle::UNDEFINED, exception: true)
330+
if !TrufflePrimitive.undefined?(precision)
331+
precision = Truffle::Type.rb_num2int(precision)
332+
if precision < 0
333+
if exception
334+
raise ArgumentError, 'negative precision'
335+
else
336+
return nil
337+
end
338+
end
339+
end
340+
341+
case value
342+
when nil
343+
if exception
344+
raise TypeError, "can't convert nil into BigDecimal"
345+
else
346+
return nil
347+
end
348+
when true
349+
if exception
350+
raise TypeError, "can't convert true into BigDecimal"
351+
else
352+
return nil
353+
end
354+
when false
355+
if exception
356+
raise TypeError, "can't convert false into BigDecimal"
357+
else
358+
return nil
359+
end
360+
when BigDecimal, Integer, Float, Rational, String
361+
# conversion handled in primitive
362+
else
363+
if exception
364+
value = StringValue(value)
365+
else
366+
value = Truffle::Type.rb_check_convert_type(count, String, :to_str)
367+
if value.nil?
368+
return nil
369+
end
370+
end
371+
end
372+
TrufflePrimitive.bigdecimal_new value, precision, exception
331373
end
332374
end
333375

spec/ruby/library/bigdecimal/BigDecimal_spec.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,12 @@
4646
BigDecimal(" \t\n \r-Infinity \n").infinite?.should == -1
4747
end
4848

49+
it "coerces the value argument with #to_str" do
50+
initial = mock("value")
51+
initial.should_receive(:to_str).and_return("123")
52+
BigDecimal(initial).should == BigDecimal("123")
53+
end
54+
4955
ruby_version_is ""..."2.6" do
5056
it "ignores trailing garbage" do
5157
BigDecimal("123E45ruby").should == BigDecimal("123E45")

0 commit comments

Comments
 (0)