Skip to content

Commit

Permalink
Fix error where to_currency_code/1 would break for countries with no … (
Browse files Browse the repository at this point in the history
#48)

* Fix error where to_currency_code/1 would break for countries with no currencies

* Return Cldr.UnknownCurrencyError from to_currency_code/1 when no currency exists
  • Loading branch information
Stroemgren authored Nov 24, 2024
1 parent f1639c3 commit 5fb2d84
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
8 changes: 5 additions & 3 deletions lib/cldr/territory.ex
Original file line number Diff line number Diff line change
Expand Up @@ -813,6 +813,9 @@ defmodule Cldr.Territory do
iex> Cldr.Territory.to_currency_code("cu")
{:ok, :CUP}
iex> Cldr.Territory.to_currency_code(:CQ)
{:error, {Cldr.UnknownCurrencyError, "No currencies for :CQ were found"}}
"""
@doc since: "1.2.0"
@spec to_currency_code(atom() | String.t() | LanguageTag.t(), Keyword.t()) :: {:ok, atom() | String.t() | charlist()} | {:error, {module(), String.t()}}
Expand All @@ -823,11 +826,11 @@ defmodule Cldr.Territory do
{:error, reason} -> {:error, reason}

{:ok, [code | _]} -> {:ok, code}

{:ok, []} -> {:error, {Cldr.UnknownCurrencyError, "No currencies for #{inspect territory_code} were found"}}
end
end



@doc """
The same as `to_currency_code/2`, but raises an exception if it fails.
Expand Down Expand Up @@ -862,7 +865,6 @@ defmodule Cldr.Territory do
end
end


@doc """
A helper method to get a territory's currency codes.
Returns `{:ok, list}` if successful, otherwise `{:error, reason}`.
Expand Down
28 changes: 28 additions & 0 deletions test/territory_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -545,4 +545,32 @@ defmodule Cldr.TerritoryTest do
Territory.known_territory_subdivisions(:NOPE, TestBackend.Cldr)
end
end

describe "to_currency_code/1" do
test "with valid params" do
assert {:ok, :USD} == Territory.to_currency_code(:US)
assert {:ok, "DKK"} == Territory.to_currency_code(:DK, as: :binary)
end

test "with invalid params" do
assert {:error, {Cldr.UnknownCurrencyError, "No currencies for :CQ were found"}} == Territory.to_currency_code(:CQ)
assert {:error, {Cldr.UnknownTerritoryError, "The territory \"zz\" is unknown"}} == Territory.to_currency_code("zz")
end
end

describe "to_currency_code!/1" do
test "with valid params" do
assert :GBP == Cldr.Territory.to_currency_code!(:UK)
assert "SEK" == Cldr.Territory.to_currency_code!(:SE, as: :binary)
end

test "with invalid params" do
assert_raise Cldr.UnknownCurrencyError, "No currencies for :CQ were found", fn ->
Territory.to_currency_code!(:CQ)
end
assert_raise Cldr.UnknownTerritoryError, "The territory \"zzzzz\" is unknown", fn ->
Territory.to_currency_code!("zzzzz")
end
end
end
end

0 comments on commit 5fb2d84

Please sign in to comment.