defmodule User do
@enforce_keys [:email]
defstruct [:email, name: "anonymous", admin?: false]
# A constructor is the idiomatic place to validate.
# `__MODULE__` is the current module's name, and
# `struct!/2` builds the struct from a keyword list,
# raising on unknown or missing keys.
def new(fields) do
user = struct!(__MODULE__, fields)
if String.contains?(user.email, "@"),
do: {:ok, user},
else: {:error, :invalid_email}
end
end