Piping input when shelling out

On 9/19/06, [email protected] [email protected] wrote:

you’re making it pretty hard on yourself:

 harp:~ > cat a.rb
 cat = IO.popen 'cat', 'r+'

Interestingly, I just found a use for popen this morning. I was
playing around with letting open-uri use an ‘scp’ url.

This is a complete hack based on the URI::HTTP class, and it’s pretty
rudimentary. Even though it’s an ‘scp’ uri, it uses ssh internally.

As far as I can tell, without looking too hard, open-uri only supports
opening a URI for reading.

rick@frodo:/public/rubyscripts$ cat uris/scp.rb

= uri/scp.rb

Author:: Rick DeNatale

License:: You can redistribute it and/or modify it under the same

term as Ruby.

require ‘uri/generic’

module URI

scp_URI = “scp://” [ userinfo “@” ] host [ “:” port ]

[ ; parameter = value ] [ abs_path ]

class SCP < Generic
DEFAULT_PORT = 22

COMPONENT = [
  :scheme,
  :userinfo, :host, :port,
  :path
].freeze

#
# == Description
#
# Create a new URI::SCP object from components of URI::SCP with
# check.  It is scheme, userinfo, host, port, and path. It

provided by an Array of a Hash.
#
def self.build(args)
tmp = Util::make_components_hash(self, args)
return super(tmp)
end

#
# == Description
#
# Create a new URI::SCP object from ``generic'' components with no
# check.
#
def initialize(*arg)
  super(*arg)
end

def ssh_command
  result = ["ssh "]
  result << "-p" + port.to_s + " " unless port == 22
  result << user + "@" if user
  result << host + " cat ~"
  result << path
  result.join('')
end

def open(&b)
  IO.popen(ssh_command, &b)
end

end

@@schemes[‘SCP’] = SCP
end


Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/