How would you idiomatically call each of A
module’s functions until you get a first {:ok, ...}
return?
defmodule A do
def a(), do: {:error, 1}
def b(), do: {:ok, 2}
# ...
end
Is this the best one can do?
case {A.a, A.b} do
{{:ok, a}, _} -> a
{_, {:ok, b}} -> b
_ -> {:error, ""}
end
To avoid the XY-problem, I’m Jason.decode
ing an incoming JSON and then, in parse/1
below, trying to build one of predefined structs from it - StructN
presents one of N possible events.
defmodule StructN do
embedded_schema do
field :uuid, :string
# ...
end
# def changeset ...
def new(params) do
%__MODULE__{}
|> changeset(params)
|> apply_action(:build)
end
end
def parse(input) do
with {:ok, json} <- Jason.decode(input) do
case {StructA.new(json), StructB.new(json), ...} do
{{:ok, a}, _, ...} -> a
{_, {:ok, b}, ...} -> b
_ -> {:error, ""}
end
end
end
Could anything be improved with this approach?