A metric weight type for Ash.
Stored canonically as integer milligrams (BIGINT in Postgres), with
ergonomic conversions to grams and kilograms via Decimal to avoid float
drift.
Usage
attribute :weight, AshWeight, constraints: [min: 0]
AshWeight.new(1.5, :g) # => %AshWeight{mg: 1500}
AshWeight.from_kg("2.25") # => %AshWeight{mg: 2_250_000}
AshWeight.to_kg(weight) # => #Decimal<0.0015>
to_string(AshWeight.from_kg(1.5)) # => "1.5 kg"Accepted input shapes for Ash.Type.cast_input/3:
%AshWeight{}- integer — treated as milligrams
{value, :mg | :g | :kg}— explicit unit%{value: _, unit: _}/%{"value" => _, "unit" => _}— form datanil
Summary
Functions
Adds two weights.
Compares two weights. Returns :lt, :eq, or :gt.
Builds a weight from a gram value (mass × 1_000 mg).
Builds a weight from a kilogram value (mass × 1_000_000 mg).
Builds a weight from a milligram value.
Multiplies a weight by a scalar.
Builds a weight from value in the given metric unit (default :mg).
Subtracts b from a.
Returns the weight in grams as a Decimal.
Returns the weight in kilograms as a Decimal.
Returns the weight in integer milligrams.
Types
@type t() :: %AshWeight{mg: integer()}
@type unit() :: :mg | :g | :kg
Functions
Adds two weights.
Compares two weights. Returns :lt, :eq, or :gt.
Builds a weight from a gram value (mass × 1_000 mg).
Builds a weight from a kilogram value (mass × 1_000_000 mg).
Builds a weight from a milligram value.
Multiplies a weight by a scalar.
Builds a weight from value in the given metric unit (default :mg).
value may be an integer, float, Decimal, or numeric string. Internally
normalized through Decimal arithmetic and rounded to integer milligrams,
so new(0.1, :g) is exactly 100 mg with no float drift.
Subtracts b from a.
Returns the weight in grams as a Decimal.
Returns the weight in kilograms as a Decimal.
Returns the weight in integer milligrams.