I am trying to get the directory of the temp file that is in the clipboard. I wrote the code like this
require 'clipboard'
puts Clipboard.paste
I notice that when it is text in the clipboard, the script prints out text, but when it comes to file the output is an empty string.
What is the correct way to get the file from clipboard in Ruby?
The clipboard gem uses the command line applications pbcopy
and pbpaste
on macOS. Neither application works for files in the way you are describing it.
There is more detail at this answer, but the short version is that when you select a file in the Finder and press CMD+C, macOS is placing a reference to the selected file into the clipboard, and then when you press CMD+V macOS interprets the referenced file and performs a copy operation for the file to the destination location. There is a lot of behind-the-scenes work done to facilitate that operation. It is an extension of the clipboard's base functionality.
Neither pbcopy
nor pbpaste
support that functionality; they can only operate on strings. Accordingly, you cannot use the clipboard gem for this purpose.
If the file you want to copy is plaintext then you can read it into a string and then paste it into a new file. If the file is not plaintext (e.g., an image or a compiled binary) then you cannot do this.