I need to find_or_create user, but first, check if his email ends with a required domain.
Can I somehow write following code using pattern matching with/case
block?
def create_user(attrs \\ %{}) do
%User{}
|> User.changeset(attrs)
|> Repo.insert()
end
def find_or_create_user(attrs \\ %{}) do
if String.ends_with?(attrs.email, "@test.com") do
user = Repo.get_by(User, %{email: attrs.email}) # returns nil or user
if user do
{:ok, user}
else
create_user(attrs) # returns {:ok, user} or {:error, :reason}
end
else
{:error, :invalid_email_domain}
end
end
if/else
seems fine to me, but every article I see with elixir code uses pattern matching. So maybe it can be written with pattern matching, but I don't know how :) \$\endgroup\$if
looks appropriate. You can try split user name and domain and call another function to match domain, but unless you have several domains in addition to test.com, it will just bloat your code, so I'd left find_or_create as is: Much easier to recognize be it elixir, nodejs or python. \$\endgroup\$case
: Hard to prepare cases as they are dependent on one another: Why callget_by
is domain is test? \$\endgroup\$