Created
July 30, 2021 10:20
-
-
Save qhwa/5ac121c60e1b23855cfd586d8bf0012b to your computer and use it in GitHub Desktop.
ok_then
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule MyRegister do | |
@enforce_keys [:email] | |
defstruct [:email, valid?: true, errors: nil] | |
def register_user_email(email) do | |
%__MODULE__{email: email} | |
|> ok_then(&ensure_not_nil/1) | |
|> ok_then(&downcase/1) | |
|> ok_then(&validate_format/1) | |
|> ok_then(&validate_available/1) | |
# The list can goes on: | |
# |> ok_then(&do_register_user/1) | |
# |> ok_then(&send_onboard_gift/1) | |
# |> ok_then(&create_onboard_tasks/1) | |
end | |
defp ok_then(%{valid?: true} = ctx, f), do: f.(ctx) | |
defp ok_then(ctx, _f), do: ctx | |
def ensure_not_nil(%{email: email} = ctx) when is_binary(email) and email != "", | |
do: ctx | |
def ensure_not_nil(ctx), | |
do: %{ctx | errors: "email is nil", valid?: false} | |
def downcase(%{email: email} = ctx), | |
do: %{ctx | email: String.downcase(email)} | |
def validate_format(%{email: email} = ctx) do | |
if email =~ ~r/.@.+\..+$/ do | |
ctx | |
else | |
%{ctx | errors: "invalid email format", valid?: false} | |
end | |
end | |
def validate_available(%{email: email} = ctx) do | |
if unused_email?(email) do | |
ctx | |
else | |
%{ctx | errors: "email has already been taken", valid?: false} | |
end | |
end | |
defp unused_email?(_), do: true | |
end | |
MyRegister.register_user_email("foo") |> IO.inspect() | |
MyRegister.register_user_email("[email protected]") |> IO.inspect() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment