Fix error converting String to BigDecimal

This commit is contained in:
James Wu
2023-01-24 15:41:46 +09:00
committed by David Cook
parent ee30d3d139
commit b9b2fa7c94
4 changed files with 19 additions and 2 deletions

View File

@@ -22,7 +22,8 @@ module Spree
when :password
self[:value].to_s
when :decimal
BigDecimal(self[:value].to_s).round(2, BigDecimal::ROUND_HALF_UP)
BigDecimal(self[:value].to_s, exception: false)&.round(2, BigDecimal::ROUND_HALF_UP) ||
self[:value]
when :integer
self[:value].to_i
when :boolean

View File

@@ -117,7 +117,7 @@ module Spree
value.to_s
when :decimal
value = 0 if value.blank?
BigDecimal(value.to_s).round(2, BigDecimal::ROUND_HALF_UP)
BigDecimal(value.to_s, exception: false)&.round(2, BigDecimal::ROUND_HALF_UP) || value
when :integer
value.to_i
when :boolean

View File

@@ -58,6 +58,15 @@ describe Spree::Preference do
expect(pref.value_type).to eq value_type.to_s
end
it "incovertible :decimal" do
value_type = :decimal
value = "invalid"
key = "decimal_key"
pref = round_trip_preference(key, value, value_type)
expect(pref.value).to eq value
expect(pref.value_type).to eq value_type.to_s
end
it ":string" do
value_type = :string
value = "This is a string"

View File

@@ -165,6 +165,13 @@ describe Spree::Preferences::Preferable do
@a.set_preference(:if_decimal, '')
expect(@a.preferences[:if_decimal]).to eq 0.0
end
context "when the value cannot be converted to BigDecimal" do
it "returns the original value" do
@a.set_preference(:if_decimal, "invalid")
expect(@a.preferences[:if_decimal]).to eq "invalid"
end
end
end
context "converts boolean preferences to boolean values" do