I’m newly learning Elixir and just bumped again a problem that I’m not sure how to write, although I feel like there is probably a neat pattern matching solution, or maybe some better FP syntax.
How would you write the following code?
user = Repo.get_by(User, name: "jon")
unless user do
user = User |> Ecto.Query.first |> Repo.one
end
user
I feel like there is a better Elixir/FP idiom to write this?
Yes sorry if I was not clear. The code works right now, but coming from the ruby world, I was wondering if there was a syntax that would suit Elixir better (aka something for FP).
defmodule Example do
def get_user(opts), do: User |> Repo.get_by(opts) |> do_get_user()
defp do_get_user(nil), do: User |> Ecto.Query.first |> Repo.one
defp do_get_user(user), do: user
end