Skip to content

Instantly share code, notes, and snippets.

@loicginoux
Last active December 4, 2019 20:28
Show Gist options
  • Save loicginoux/eeb6ab009c9bb87a722460daa003760f to your computer and use it in GitHub Desktop.
Save loicginoux/eeb6ab009c9bb87a722460daa003760f to your computer and use it in GitHub Desktop.
Gotchas Elixirs

Gotchas Elixirs:

String Concatenation

iex> name = "Sean"
iex> "Hello " <> name
"Hello Sean"

Pin Operator

iex> greeting = "Hello"
"Hello"
iex> greet = fn
...>   (^greeting, name) -> "Hi #{name}"
...>   (greeting, name) -> "#{greeting}, #{name}"
...> end
#Function<12.54118792/2 in :erl_eval.expr/5>
iex> greet.("Hello", "Sean")
"Hi Sean"
iex> greet.("Mornin'", "Sean")
"Mornin', Sean"

Case:

res = {:ok, "Hello World"}
case res do
  {:ok, result} -> result
  {:error} -> "Uh oh!"
  _ -> "Catch all"
end

OR

iex> case {1, 2, 3} do
...>   {1, x, 3} when x > 0 ->
...>     "Will match"
...>   _ ->
...>     "Won't match"
...> end
"Will match"

With

Ceci

case Repo.insert(changeset) do
  {:ok, user} ->
    case Guardian.encode_and_sign(resource, :token, claims) do
      {:ok, jwt, full_claims} ->
        important_stuff(jwt, full_claims)
      error -> error
    end
  error -> error
end

Peut se réecrire comme ceci:

with
  {:ok, user} <- Repo.insert(changeset),
  {:ok, jwt, full_claims} <- Guardian.encode_and_sign(user, :token),
  do: important_stuff(jwt, full_claims)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment