Skip to content

Instantly share code, notes, and snippets.

@nihonjinrxs
Created November 5, 2019 19:52
Show Gist options
  • Save nihonjinrxs/4471f126e27bb9bab7f8defc44a73708 to your computer and use it in GitHub Desktop.
Save nihonjinrxs/4471f126e27bb9bab7f8defc44a73708 to your computer and use it in GitHub Desktop.
Testing Open3.capture3 in Ruby, using array-style command syntax vs. string-style command syntax with Unix-style pipes
require 'open3'
cli_pipe_test_array = [
"echo",
'{"some": "json", "data": 345, "here": true}',
"|",
"jq",
'".data"',
"|",
"xargs",
"echo"
]
cli_pipe_test_string = %Q@echo '{"some": "json", "data": 345, "here": true}' | jq ".data" | xargs echo@
# customize the environment variables passed to the worker container
def spawn_env(custom_env = {})
env_vars = {}
env_vars.merge(custom_env)
end
# `capture3` supports a hash of options to specify process attributes
# see Process.spawn http://ruby-doc.org/core-2.5.1/Process.html#method-c-spawn
# for available options.
# override this method to suite your needs
def spawn_attributes
{}
end
[cli_pipe_test_array, cli_pipe_test_string].each do |cli_pipe_test|
stdout, stderr, status = Open3.capture3(
spawn_env,
*cli_pipe_test,
spawn_attributes
)
p ""
p "COMMAND:"
p cli_pipe_test
p ""
p "STDOUT:"
p stdout
p ""
p "STDERR:"
p stderr
p ""
p "STATUS:", status
end
$ ruby capture3_test.rb
""
"COMMAND:"
["echo", "{\"some\": \"json\", \"data\": 345, \"here\": true}", "|", "jq", "\".data\"", "|", "xargs", "echo"]
""
"STDOUT:"
"{\"some\": \"json\", \"data\": 345, \"here\": true} | jq \".data\" | xargs echo\n"
""
"STDERR:"
""
""
"STATUS:"
#<Process::Status: pid 75814 exit 0>
""
"COMMAND:"
"echo '{\"some\": \"json\", \"data\": 345, \"here\": true}' | jq \".data\" | xargs echo"
""
"STDOUT:"
"345\n"
""
"STDERR:"
""
""
"STATUS:"
#<Process::Status: pid 75815 exit 0>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment