Guards and Control Flow
Guard: when
If
if (condition, do: this, else: that)
if(condition, [do: this, else: that])
if(condition, [{:do, this}, {:else, that}])
if true do
this
else
that
end
if(true, do: (this), else: (that))
if true do
this
that
end
if(true, do: (
this
that
))
falsey = false or nil
truthy = everything that is not false or nil
Case
case condition do
x when x in [false, nil] -> cases...
_ -> cases..
end
Case is most commonly used for the insert actions
# liveview
def save_post(socket, :new, post_params) do
case Blog create_post(post_params) do
{:ok, post } ->
notify_parent({:saved, post})
{:no_reply, socket |> put_flash(:info, "ok")} |> push_patch(to: socket.assigns.patch}
{:ok, %Ecto.changeset = changeset } ->
{:no_reply, assign_form(socket, changeset)}
# phoenix
def create(conn, %{"email" => email_params}) do
case Emails.create_email(email_params) do
Cond
cond do
age >= 10 -> IO.puts "A"
age <= 10 -> IO.puts "B"
true -> IO.puts "Z" # fallback
end
with
Assuming a chain of conditions:
m = %{a: 1, c: 3}
a =
with {:ok, number} <- Map.fetch(m, :a),
true <- is_even(number) do
IO.puts "#{number} divided by 2 is #{div(number, 2)}"
:even
else
:error ->
IO.puts("We don't have this item in map")
:error
_ ->
IO.puts("It is odd")
:odd
end
with {:ok, variable} <- Module.action(changeset),
{:ok, token, full_claims} <- Guardian.encode_and_sign(user, :token, claims) do
important_stuff(token, full_claims)
end