A repository of bitesize articles, tips & tricks
(in both English and French) curated by Mirego’s team.

Using Elixir’s “tap” to improve introspection in pipelines

Elixir makes it pretty easy to inspect data that is passed through a pipeline:

map = %{one: "un", two: "deux"}
  |> Map.put(:three, "three")
  |> IO.inspect()
  |> Map.put(:four, "quatre")

will print this to stdout:

%{one: "un", two: "deux", three: "trois"}

before returning:

%{one: "un", two: "deux", three: "trois", four: "quatre"}

But what if we want to print something more specific, like only the map keys?

map = Map.put(%{one: "un", two: "deux"}, :three, "three")

IO.inspect(Map.keys(map))

map = Map.put(map, :four, "quatre")

We had to break our nice pipeline 😞

But since Elixir 1.12, we can use Kernel.tap/2 to keep our pipeline intact while inspecting data a bit more:

map = %{one: "un", two: "deux"}
  |> Map.put(:three, "three")
  |> tap(&IO.inspect(Map.keys(&1)))
  |> Map.put(:four, "quatre")

will print this to stdout:

[:one, :two, :three]

before returning:

%{one: "un", two: "deux", three: "trois", four: "quatre"}

🎉