Skip to content

Commit

Permalink
return nil when the fuzzy parser is not able to guess
Browse files Browse the repository at this point in the history
  • Loading branch information
elfassy committed Oct 7, 2024
1 parent 1c28bad commit 87739aa
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
6 changes: 4 additions & 2 deletions lib/money/parser/fuzzy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ def self.parse(input, currency = nil, **options)
def parse(input, currency = nil, strict: false)
currency = Money::Helpers.value_to_currency(currency)
amount = extract_amount_from_string(input, currency, strict)
Money.new(amount, currency)
if amount
Money.new(amount, currency)
end
end

private
Expand All @@ -93,7 +95,7 @@ def extract_amount_from_string(input, currency, strict)

if number.empty?
if !strict
return '0'
return nil
else
raise MoneyFormatError, "invalid money string: #{input}"
end
Expand Down
4 changes: 2 additions & 2 deletions spec/parser/accounting_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
expect(@parser.parse("")).to eq(Money.new)
end

it "parses an invalid string to $0" do
expect(@parser.parse("no money", 'USD')).to eq(Money.new(0, 'USD'))
it "parses an invalid string when not strict to nil" do
expect(@parser.parse("no money", 'USD')).to eq(nil)
end

it "parses a single digit integer string" do
Expand Down
10 changes: 8 additions & 2 deletions spec/parser/fuzzy_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,15 @@
expect(@parser.parse("")).to eq(Money.new(0, Money::NULL_CURRENCY))
end

it "parses an invalid string when not strict" do
expect(@parser.parse("no money", 'USD')).to eq(Money.new(0, 'USD'))
it "parses an invalid string when not strict to nil" do
expect(@parser.parse("no money", 'USD')).to eq(nil)
end

it "parses a badly formatted numeric string when not strict to the closest approximation" do
expect(@parser.parse("1..", 'USD')).to eq(Money.new(1, 'USD'))
expect(@parser.parse("1.000", 'USD')).to eq(Money.new(1, 'USD'))
expect(@parser.parse("1.1.1", 'USD')).to eq(Money.new(111, 'USD'))
expect(@parser.parse("1,1.11", 'USD')).to eq(Money.new(11.11, 'USD'))
end

it "parses raise with an invalid string and strict option" do
Expand Down

0 comments on commit 87739aa

Please sign in to comment.