def userselect(%{id: id} = user), do: …
def userselect(%{email: email} = user), do: …
def userselect(%{username: username} = user), do: …
def userselect(_), do: …
Since you now have a match on id
, email
, or username
you may be able to even rewrite the “inner” block a bit.
Since all the case
are identical, I’d even move them into a helper function, making your blocks look like this:
defp sel_user(nil), do: {:error, "Something went wrong"}
defp sel_user(user), do: {:ok, user}
def userselect(%{id: id}), do: User |> Repo.get(id) |> sel_user()
def userselect(%{email: email}), do: User |> Repo.get(email) |> sel_user()
def userselect(%{username: username}), do: User |> Repo.get(username) |> sel_user()
def userselect(_), do: sel_user(nil)
Next step were to create those function heads from a list using metaprogramming, they are the same except for the key to match on… But to be honest, I’d do that only for more than 5 keys, you don’t gain much for less, maybe even you loose a lot if meta-ing to early