From dd3c6c5e594291a8c5f0d30c3e84208b265fb2f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B8ren=20Siersted=20Mikkelsen?= Date: Fri, 11 Apr 2025 10:08:44 +0200 Subject: [PATCH] feat: add JSON encoding support for Quantity - implement Jason.Encoder for Quantity to allow JSON encoding - add Jason as a dependency in mix.exs (it is part of mix already) --- lib/quantity.ex | 11 ++++++++++- mix.exs | 1 + test/quantity_test.exs | 4 ++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/quantity.ex b/lib/quantity.ex index 9d2e131..b81c198 100644 --- a/lib/quantity.ex +++ b/lib/quantity.ex @@ -146,7 +146,7 @@ defmodule Quantity do @doc """ Encodes the quantity as a string. The result is parsable with parse/1 - If the exponent is positive, encode usinge the "raw" format to preserve precision + If the exponent is positive, encode using the "raw" format to preserve precision iex> Quantity.new(42, -1, "db") |> Quantity.to_string() "4.2 db" @@ -351,6 +351,15 @@ defmodule Quantity do end end + defimpl Jason.Encoder do + @impl Jason.Encoder + def encode(value, opts) do + value + |> Quantity.to_string() + |> Jason.Encode.string(opts) + end + end + # Normalizes unit to a standard form: # * Shorten unit as much as possible # * At most one :div (with possibly many :mults on each side) diff --git a/mix.exs b/mix.exs index 3ffc5e8..42e5a75 100644 --- a/mix.exs +++ b/mix.exs @@ -36,6 +36,7 @@ defmodule Quantity.MixProject do [ # Decimal {:decimal, "~> 2.0"}, + {:jason, "~> 1.4"}, # Documentation {:ex_doc, "~> 0.21", only: :dev, runtime: false}, diff --git a/test/quantity_test.exs b/test/quantity_test.exs index 6c8a934..c708770 100644 --- a/test/quantity_test.exs +++ b/test/quantity_test.exs @@ -55,6 +55,10 @@ defmodule QuantityTest do assert Quantity.to_string(~Q[42]) == "42" end + test "encode to json from map" do + assert %{quantity: ~Q[12.45 DKK]} |> Jason.encode!() == ~S|{"quantity":"12.45 DKK"}| + end + test "for non-number decimals" do ["inf", "-inf", "nan"] |> Enum.each(fn not_number ->