1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
def self.capture_system(*args) args = args.flatten.compact.collect { |arg| arg.to_s } return false if args.blank? rd, wr = IO.pipe pid = fork do rd.close $stdout.reopen wr $stderr.reopen wr yield if block_given? exec(*args) rescue nil exit! 1 # never gets here unless exec threw or failed end wr.close out = String.new out << rd.read until rd.eof? Process.wait raise unless $?.success? out end
Refactorings
No refactoring yet !
Is there a shorter way to do this? Basically, I don't want anything outputted to the current irb session, but I want the variable 'out' to be the output from the fork. Command 'puts capture_system('which', 'git')' should work at the end of it.