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!

Want the latest Elixir Streams in your inbox?

    No spam. Unsubscribe any time.