# Using the pipe operator |>
data
|> Jason.encode!()
|> then(fn encoded -> File.write!("output.json", encoded) end)
# Alternative using capture syntax
data
|> Jason.encode!()
|> (&File.write!("output.json", &1)).()
What is the question, how you can pipe writing to file?
The option with then should be good enough, I would avoid the option with closure as it’s extremely hard to read, otherwise you can always use your own functions:
defp write_file(content, filename) do
File.write!(filename, content)
end
data
|> Jason.encode!()
|> write_file("test.json")
A word of advice, if you are just coming to elixir, you might have the itch to pipe everything, but please don’t do it, as it ends with unnecessary complexity.
I hear ya. I have a healthy dose of realism. Sometimes it’s easier to read to just create an intermediate variable. Though the pipe operator is such a convenience for tacking on an extra transformation when I need it.
Back in the day you would have also the issue with hard debugging of pipes, these days this was made trivial with introduction of dbg and then, so I would guess the only rule of the thumb is to have them readable.
I think you are breaking hearts of people that expected you to write code they would understand .
I would personally never approve a MR having such a line for application code, this is the same as someone using Integer.addExact(5, 10) in java, I need to go and open the documentation to understand wtf is going on.
I would. It’s fine, you’re technically only adding a pipe and the Kernel word compared to the other code.
There are more egregious examples of what I wouldn’t approve though, like that closure above that’s also called immediately after being defined. That’s just code golf…