2 Helpers to Keep Your Pipelines Flowing! ๐
Notes
Elixir code tends to be pipe-friendly. But sometimes that fails. You have a pesky break in your pipeline!
Here are 2 helpers that can help you keep your pipeline flowing!
Inspecting flash assign
Letโs take a conn
pipeline as an example. Suppose you have the following code:
conn
|> put_flash(:info, "User created successfully.")
|> redirect(to: ~p"/users/#{user}")
Now, assume you want to examine the flash assign weโve just set up. In order to
avoid inspecting all of conn
(which can be quite large), we have to break the
pipeline:
conn =
conn
|> put_flash(:info, "User created successfully.")
dbg(conn.assigns.flash)
conn
|> redirect(to: ~p"/users/#{user}")
But thereโs a better way! Or should I say, then
โs a better way! ๐
then
conn
|> put_flash(:info, "User created successfully.")
|> then(fn conn ->
dbg(conn.assigns.flash)
conn
end)
|> redirect(to: ~p"/users/#{user}")
then
is just another step of the pipeline that takes a function where the
first argument will be the previous return value (in our case conn
).
The trick is, since we want to keep the pipeline flowing, we have to also return
conn
(for redirect/2
to work).
But sometimes, as is our case, we only want to perform a side-effect. And for
that, we can tap
in our good friend.
tap
conn
|> put_flash(:info, "User created successfully.")
|> tap(fn conn ->
dbg(conn.assigns.flash)
end)
|> redirect(to: ~p"/users/#{user}")
tap
passes the value (conn
) into a function and then returns the value
(conn
) that was passed into the function. Excellent for code with side
effects!