Skip to content

Commit c25040e

Browse files
committed
feat: add answer function, will output pipe read
1 parent 5c6dcb5 commit c25040e

File tree

4 files changed

+38
-2
lines changed

4 files changed

+38
-2
lines changed

Gemfile.lock

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
PATH
22
remote: .
33
specs:
4-
cr-exec (0.1.1)
4+
cr-exec (0.2.0)
55

66
GEM
77
remote: https://rubygems.org/

lib/cr/exec.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,18 @@ def each_line(*args, chomp: false, **options, &block)
3939
end
4040
end
4141

42+
def answer(*args, input: nil, **options)
43+
IO.popen(*args, **options) do |pipe|
44+
if input.is_a? Array
45+
input.each { |cmd| pipe.puts(cmd) }
46+
else
47+
pipe.puts(input)
48+
end
49+
pipe.close_write
50+
pipe.read
51+
end
52+
end
53+
4254
def system?(...)
4355
system(...) ? true : false
4456
end

lib/cr/exec/version.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@
22

33
module Cr
44
module Exec
5-
VERSION = "0.1.1"
5+
VERSION = "0.2.0"
66
end
77
end

spec/cr/exec_spec.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,30 @@
5555
expect(Cr::Exec.each_line({ "FOO" => "bar" }, "echo $FOO", chomp: true)).to eq ["bar"]
5656
end
5757

58+
it "answer no need input" do
59+
expect(Cr::Exec.answer("uname", "r+")).to eq "Linux\n"
60+
end
61+
62+
it "answer with cmd" do
63+
expect(Cr::Exec.answer("bash", "r+", input: "uname")).to eq "Linux\n"
64+
end
65+
66+
it "answer with cmd array" do
67+
expect(Cr::Exec.answer("bash", "r+", input: %w[uname uname])).to eq "Linux\nLinux\n"
68+
end
69+
70+
it "answer with space included cmd array" do
71+
expect(Cr::Exec.answer("bash", "r+", input: ["ls spec", "uname"])).to eq "cr\nspec_helper.rb\nLinux\n"
72+
end
73+
74+
it "answer with ruby embbed cmd" do
75+
expect(Cr::Exec.answer("bash", "r+", input: "echo #{Array(1..5)}")).to eq "[1, 2, 3, 4, 5]\n"
76+
end
77+
78+
it "answer with ruby array" do
79+
expect(Cr::Exec.answer("bash", "r+", input: Array.new(2, "uname"))).to eq "Linux\nLinux\n"
80+
end
81+
5882
it "always return bool" do
5983
p system("unamea")
6084
expect(Cr::Exec.system?("unamea")).to eq false

0 commit comments

Comments
 (0)