Created
April 24, 2018 05:48
-
-
Save aoyama-val/502631dc6e20d7987b9fc7b8bd521767 to your computer and use it in GitHub Desktop.
Build curl command lines with Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "uri" | |
require "open3" | |
class CurlBuilder | |
def build(base_url:, method: "GET", params: {}, headers: {}, body_filename: nil, verbose: true, silent: true, options: "") | |
url = base_url | |
url += "?" + URI.encode_www_form(params) unless params.empty? | |
cmd = "curl -X #{method} '#{url}'" | |
cmd += " -d '@#{body_filename}'" if body_filename | |
cmd += " " + headers.map {|k, v| "-H '#{k}: #{v}'"}.join(" ") + " " unless headers.empty? | |
cmd += " -v " if verbose | |
cmd += " -s " if silent | |
cmd += options | |
return cmd | |
end | |
def exec(*args, **kwargs) | |
cmd = build(*args, **kwargs) | |
o, e, s = Open3.capture3(cmd) | |
print "\e[0;34m" | |
puts cmd | |
print "\e[0m" | |
print "\e[0;33m" | |
puts e | |
print "\e[0m" | |
print "\e[0;32m" | |
puts o | |
print "\e[0m" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
CurlBuilder#exec
builds a command line and executes it. The executed command line, stderr, and stdout are printed with different colors. Handy in development.