1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-06 16:48:01 +00:00

Add Using When Clauses In A With Construct as an elixir til

This commit is contained in:
jbranchaud
2019-03-13 09:46:11 -05:00
parent 1873dd8328
commit 1eb152b370
2 changed files with 23 additions and 1 deletions

View File

@@ -0,0 +1,21 @@
# Using When Clauses In A With Construct
Because Elixir's `with` construct supports the full power of the language's
pattern matching, we can use `when` clauses to further narrow down our
matches.
For instance, if we want to match against the response to an API request,
but only for response status codes in the 2xx range, we can do something
like the following:
```elixir
with %{status_code: code, body: body}
when code >= 200 && code < 300 <- HTTPoison.get!(url),
{:ok, decoded_body} <- Poison.decode(body) do
{:ok, decoded_body}
end
```
See the [docs for
`with`](https://hexdocs.pm/elixir/Kernel.SpecialForms.html#with/1) for more
details.