Copy to Clipboard in Ruby
Greetings, friends! A few days ago, I was using pry, a runtime developer console for Ruby, to debug an issue in a Rails application when I encountered an issue. It went something this...
I had multiple choices. I could write the output to a file and view the whole list there, or I could change my pager, so I'm not using the "less" program inside the terminal to display the output piece by piece. Then, I thought, "Why not just copy the output to the clipboard?" Light bulb! 💡
On MacOS, the program, "pbcopy," allows you to copy text from standard input (stdin) into the clipboard buffer on your operating system. After running it, this command will pipe "Hello World!" into your clipboard. If you try to paste text anywhere, you should see that "Hello World!" will be pasted.
echo 'Hello World!' | pbcopy
Most programming languages provide a way to spin off child processes or subprocesses that allow you to execute programs such as "ls" to list out files on your machine for MacOS and Linux. In Ruby, you can use the IO.popen
method to run a specified command as a subprocess.
The idea is to run pbcopy through Ruby, so while we are in pry, we can programatically copy objects to our clipboard. Then, we can paste the content somewhere else like VS Code to inspect the object or share it with a coworker.
For MacOS,
obj = {a: "Hello World!", b: "Hi Earth!"}
IO.popen('pbcopy', 'w') { |pipe| pipe.puts obj }
For Windows,
obj = {a: "Hello World!", b: "Hi Earth!"}
IO.popen('clip', 'w') { |pipe| pipe.puts obj }
An alternative approach would be to use the system
method to execute a command in a subshell:
str = "This is fun!"
system "echo #{str} | pbcopy"
An even easier way would be to use backticks:
str = "This is much easier."
`echo #{str} | pbcopy`
Each of these approaches have their own advantages and disadvantages when used to run other commands. For the purpose of copying to the clipboard, each approach should be equally sufficient. Now, the next time you're debugging Ruby code and need to copy something to the clipboard, you have the power! Happy coding!