Skip to content

Commit

Permalink
Fix to handle custom structs with new function that returns an ok|err…
Browse files Browse the repository at this point in the history
…or tuple
  • Loading branch information
bbalser committed Jun 8, 2020
1 parent 3aa4a5a commit 26d1506
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 6 deletions.
12 changes: 8 additions & 4 deletions lib/json_serde/impls/any.ex
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ end

defimpl JsonSerde.Deserializer, for: Any do
require JsonSerde
import Brex.Result.Base, only: [fmap: 2, ok: 1]
import Brex.Result.Base, only: [fmap: 2, ok: 1, bind: 2]
import Brex.Result.Mappers

def deserialize(%module{}, map) do
convert(map)
|> fmap(&construct(module, &1))
|> bind(&construct(module, &1))
end

def deserialize(_, term) do
Expand All @@ -38,8 +38,8 @@ defimpl JsonSerde.Deserializer, for: Any do
defp construct(module, map) do
Code.ensure_loaded?(module)
case function_exported?(module, :new, 1) do
true -> apply(module, :new, [map])
false -> struct(module, map)
true -> apply(module, :new, [map]) |> wrap()
false -> struct(module, map) |> ok()
end
end

Expand All @@ -54,4 +54,8 @@ defimpl JsonSerde.Deserializer, for: Any do
|> fmap(&Map.new/1)
end

defp wrap({:ok, _} = ok), do: ok
defp wrap({:error, _} = error), do: error
defp wrap(value), do: {:ok, value}

end
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ defmodule JsonSerde.MixProject do
def project do
[
app: :json_serde,
version: "1.0.1",
version: "1.0.2",
elixir: "~> 1.8",
start_permanent: Mix.env() == :prod,
description: description(),
Expand Down
2 changes: 1 addition & 1 deletion test/structs_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ defmodule JsonSerde.StructTests do
defstruct [:name, :age, :birthdate]

def new(map) do
struct(__MODULE__, Map.update!(map, :name, &String.upcase/1))
{:ok, struct(__MODULE__, Map.update!(map, :name, &String.upcase/1))}
end
end

Expand Down

0 comments on commit 26d1506

Please sign in to comment.