Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve Fuzzy parsing with invalid strings #316

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading