Skip to content

Commit 866080f

Browse files
committed
feat: yield Process::Pipe when block.arity == 1
1 parent a767d4f commit 866080f

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

lib/rb/process.rb

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,19 @@
55
require_relative "process/version"
66

77
module Process
8-
def self.run(*args, output: STDOUT, error: STDERR, **options)
8+
class Pipe
9+
attr_reader :input
10+
attr_reader :output
11+
attr_reader :error
12+
13+
def initialize(input, output, error)
14+
@input = input
15+
@output = output
16+
@error = error
17+
end
18+
end
19+
20+
def self.run(*args, output: STDOUT, error: STDERR, **options, &block)
921
output_strio = StringIO.new
1022
error_strio = StringIO.new
1123

@@ -34,14 +46,23 @@ def self.run(*args, output: STDOUT, error: STDERR, **options)
3446

3547
if block_given?
3648
begin
37-
yield in_w, out_r, err_r
49+
case block.arity
50+
when 1
51+
yield Pipe.new(in_w, out_r, err_r)
52+
when 2
53+
yield in_w, out_r
54+
when 3
55+
yield in_w, out_r, err_r
56+
else
57+
raise ArgumentError.new("block must take 1 to 3 arguments")
58+
end
3859
rescue StandardError => e
3960
Process.detach(pid)
4061
raise e
4162
end
4263
end
4364

44-
in_w.close
65+
in_w.close unless in_w.closed?
4566
out_w.close
4667
err_w.close
4768

spec/rb/process_spec.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@
4545
end
4646

4747
it "answer with cmd with ruby style" do
48+
expect(Process.run("bash") { |pipe| pipe.input.puts "uname" }).to eq "Linux\n"
49+
expect(Process.run("bash") { |i, _o| i.puts "uname" }).to eq "Linux\n"
4850
expect(Process.run("bash") { |i, _o, _e| i.puts "uname" }).to eq "Linux\n"
4951
end
5052

0 commit comments

Comments
 (0)