Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active December 14, 2015 18:39
Show Gist options
  • Save havenwood/5131003 to your computer and use it in GitHub Desktop.
Save havenwood/5131003 to your computer and use it in GitHub Desktop.
Copy and Paste to OS X, BSD, and Linux clipboards with Ruby.
class Clipboard
CopyPaste = Struct.new :copy, :paste
def initialize
cmds = [['pbcopy', 'pbpaste'],
['xclip', 'xclip -o'],
['xsel', 'xsel -o']]
cmds.map! do |cmd|
CopyPaste.new cmd.first, cmd.last
end
@clipboard = cmds.find do |cmd|
system "which #{cmd.copy} > /dev/null"
end
end
def copy this
IO.popen @clipboard.copy, 'w' do |io|
io.print this
end
end
def paste
`#{@clipboard.paste}`
end
end
clip = Clipboard.new
clip.copy 'hiya'
#=> nil
clip.paste
#=> "hiya"
@toctan
Copy link

toctan commented Oct 7, 2013

I have tried to implement this in Linux, but when I tried to call xclip using the backtick, the program hangs.

2.0.0p247 > system 'xclip .bashrc'
 => true 
2.0.0p247 > `xclip .bashrc`
# irb hangs!

Do you have any idea what's going on? What's the difference between backtick and system? Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment