Skip to content

Commit

Permalink
Implement JSON.Encoder if available (#215)
Browse files Browse the repository at this point in the history
  • Loading branch information
wojtekmach authored Dec 13, 2024
1 parent 045403e commit 1a2c91d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/decimal.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
6 changes: 6 additions & 0 deletions test/decimal_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 1a2c91d

Please sign in to comment.