Money. Input. Cast
(Money.Input v0.1.0)
View Source
Casts a form-submission shape into a Money.t/0.
cast/2 consumes the four shapes a user-input pipeline can
produce:
niland blank-amount maps return{:ok, nil}— the field wasn't filled in.Money.t/0round-trips unchanged.%{"amount", "currency"}(or%{amount, currency}) — the nested form-submission shape that<.money_input>produces and thatMoney.Ecto.Composite.Typeaccepts. The amount field is built withMoney.new/3; pass:localeif you need to parse a locale-formatted amount string.A bare binary (
"$1,234.56","1.234,56") delegates toMoney.parse/2. Money.parse already handles surrounding whitespace, accounting parens, currency symbols and ISO codes.
The function is modelled after Money.Ecto.Composite.Type.cast/2
(in money_sql) so behaviour stays consistent across the two
paths. We host our own copy to avoid taking on ecto_sql as a
hard dependency.
Summary
Functions
Casts a form-submission value to a Money.t/0.
Types
Functions
Casts a form-submission value to a Money.t/0.
Arguments
inputis the value to cast (seeinput/0).optionsis a keyword list of options forwarded toMoney.new/3for map inputs andMoney.parse/2for string inputs.
Options
:locale— locale to use when parsing a locale-formatted amount string. Defaults toLocalize.get_locale/0.:currency— fallback currency atom used only when the submitted map omits thecurrencykey. Has no effect when the map provides one.
Returns
{:ok, Money.t()}on success.{:ok, nil}for blank input —nil,"", a map with an emptyamount, or a map with noamountkey at all.{:error, term()}if the cast fails — typically an{exception, message}tuple.
Examples
iex> Money.Input.Cast.cast(%{"amount" => "1234.56", "currency" => "USD"})
{:ok, Money.new(:USD, "1234.56")}
iex> Money.Input.Cast.cast(%{"amount" => "1.234,56", "currency" => "EUR"}, locale: :de)
{:ok, Money.new(:EUR, "1234.56")}
iex> Money.Input.Cast.cast(%{"amount" => "10"}, currency: :JPY)
{:ok, Money.new(:JPY, "10")}
iex> Money.Input.Cast.cast(%{"amount" => "", "currency" => "USD"})
{:ok, nil}
iex> Money.Input.Cast.cast(nil)
{:ok, nil}
iex> Money.Input.Cast.cast(Money.new(:GBP, "5.00"))
{:ok, Money.new(:GBP, "5.00")}