"Programs must be written for people to read, and only incidentally for machines to execute." ― Abelson & Sussman

With statement in Elixir

The with statement in Elixir is a compelling way to chain together statements that depend on each other. However, I was confused on how to respond differently, depending on which statement went wrong. Luckily I came across Elixir’s with statement is fantastic article which showed me the way.

Each chained function call returns a tuple with an atom that helps us know exactly where things went wrong in the chain.

Now we are able to chain statements and in the else clause deal with the specific statement which did not respond as we would have liked it to. In the example below we will first try to look up an user, create a customer from them, add a subcription and subsequently update the user.

1def create_subscription(email, plan_id, payment_method_id) do
2 with {:user_lookup, %User{customer_id: nil, name: name} = user} <-
3 {:user_lookup, Repo.get_by(User, email: email)},
4 {:customer_creation, {:ok, %Stripe.Customer{id: customer_id}}} <-
5 {:customer_creation,
6 Stripe.Customer.create(%{
7 name: name,
8 email: email,
9 payment_method: payment_method_id,
10 invoice_settings: %{
11 default_payment_method: payment_method_id
12 }
13 })},
14 {:subscription_creation, {:ok, %Stripe.Subscription{id: subscription_id}}} <-
15 {:subscription_creation,
16 Stripe.Subscription.create(%{customer: customer_id, items: [%{plan: plan_id}]})},
17 {:user_update, {:ok, %User{}}} <-
18 {:user_update,
19 User.update(user, %{customer_id: customer_id, subscription_id: subscription_id})} do
20 {:ok, :subscription_created}
21 else
22 {:user_lookup, _} ->
23 {:error, :user_lookup_error}
25 {:customer_creation, _} ->
26 {:error, :customer_creation_error}
28 {:subscription_creation, _} ->
29 {:error, :subscription_creation_error}
31 {:user_update, _} ->
32 {:error, :user_update_error}
34 err ->
35 {:error, err}
36 end