Chaining Elixir's "with" context

Chaining Elixir’s “with” context

Elixir has a powerful withconstruct that isn’t availabe in ruby. This is an elegant pattern for a language. It can be used to pull out individual values or it can be chained.

Individual value example (yes, a bit contrived):

def divide(values) do
  with {:ok, dividend} <- Map.fetch(values, :dividend),
       {:ok, divisor} <- Map.fetch(values, :divisor) do
    {:ok, dividend / divisor}
  end
end

You can also match on more than just tuples and chain the values. Here’s an example using the JSON library Poison’s decode.

def fetch_json(url)
  with %{status_code: 200, body: raw_body} <- HTTPoison.get!(url),
      {:ok, json} <- Poison.decode(raw_body) do
    {:ok, json}
  end
end

In fact, you have the full power of Elixir’s pattern matching available to you in your series of matches for a with construct.