Copying from the terminal is a common scenario for me. And macOS’ built-in pbcopy
command makes it very easy to do:
cat some-file.txt | pbcopy
But there isn’t something similar in Elixir that let’s you copy large terms easily. I usually have to call inspect(term, limit: :infinity)
, manually select the printed output and then copy it.
Fortunately, the Port
module in Elixir stdlib lets you work with external commands and pipe data to them.
I have a common Helpers
module that I put in many of the .iex.exs
files in my projects. These are automatically loaded whenever IEx starts. I have a copy/1
helper1 in them as well:
defmodule Helpers do
def copy(term) do
text =
if is_binary(term) do
term
else
inspect(term, limit: :infinity, pretty: true)
end
port = Port.open({:spawn, "pbcopy"}, [])
true = Port.command(port, text)
true = Port.close(port)
:ok
end
end
Using it is straight-forward:
iex(1)> User |> Repo.get!(user_id) |> Helpers.copy
:ok
- The helper above is a simplified version of Khaja Minhajuddin’s post on the same topic which is focused on Linux instead.↩
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.