From 4369bf0560e12b29c27b63c4c1f37138f0b4d8a0 Mon Sep 17 00:00:00 2001 From: Wojtek Mach Date: Thu, 12 Dec 2024 10:16:54 +0100 Subject: [PATCH] Implement `JSON.Encoder` if available --- lib/decimal.ex | 9 +++++++++ test/decimal_test.exs | 6 ++++++ 2 files changed, 15 insertions(+) diff --git a/lib/decimal.ex b/lib/decimal.ex index 69e33a9..8205680 100644 --- a/lib/decimal.ex +++ b/lib/decimal.ex @@ -2095,3 +2095,12 @@ defimpl String.Chars, for: Decimal do Decimal.to_string(dec) end end + +# TODO: remove when we require Elixir 1.18 +if Code.ensure_loaded?(JSON.Encoder) and function_exported?(JSON.Encoder, :encode, 2) do + defimpl JSON.Encoder, for: Decimal do + def encode(decimal, _encoder) do + [?", Decimal.to_string(decimal), ?"] + end + end +end diff --git a/test/decimal_test.exs b/test/decimal_test.exs index 87d9a04..0ddb468 100644 --- a/test/decimal_test.exs +++ b/test/decimal_test.exs @@ -934,4 +934,10 @@ defmodule DecimalTest do Decimal.sqrt(Decimal.new(d(3, 1, -1))) end end + + if Version.match?(System.version(), ">= 1.18.0-rc") do + test "JSON.Encoder implementation" do + assert JSON.encode!(%{x: Decimal.new("1.0")}) == "{\"x\":\"1.0\"}" + end + end end