I’ve been playing around with Phoenix in the last couple weeks and it’s been great fun!:) Amidst my dwellings, I wanted to implement an API call to create a username and send a verification e-mail in one step.
This means that both must be successful in order to procceed. Let’s forget how to revert the user creation in case the e-mail fails for now. Now, how would we do that?
In Ruby we could do something like:
It’s pretty succint right? But that if
, unless
and return
in the middle of the method… Oh boy, it pisses me off. The get_error
also kinda itches me.
Elixir’s pattern matching allows us to make the code a bit more elegant. We can expose information throughout the code in a more ordered and straight forward fashion:
Pretty cool, heh? Code’s more readable, no flow breaks and no ifs laying around. The only requirement is to follow the {:ok, whatever}
and {:error, error_struct}
format.
That said, Elixir 1.2 brought us with! Here’s an updated take on this kind of issue!
Check my other Elixir posts here.