LoginSignup
9
8

More than 5 years have passed since last update.

Rubyでcurlコマンドを組み立てる

Last updated at Posted at 2018-04-12

Gemを使わない方法

下記URLからcurl_builder.rbをダウンロードし、自分のスクリプトからrequireする。
https://gist.github.com/aoyama-val/502631dc6e20d7987b9fc7b8bd521767#file-curl_builder-rb

使い方:

CurlBuilder#buildcurlコマンドラインを組み立てて文字列として返す。

require_relative "./curl_builder.rb"

c = CurlBuilder.new
puts c.build(base_url: "http://httpbin.org/get", params: {a: 123, b: "hoge"}, headers: {"X-Hoge": "myheader"})
# => curl -X GET 'http://httpbin.org/get?a=123&b=hoge' -H 'X-Hoge: myheader'  -v  -s 
puts c.build(base_url: "http://httpbin.org/post", method: "POST", params: {a: 123, b: "hoge"}, headers: {"X-Hoge": "myheader", "Content-Type": "application/json"}, body_filename: "body.json")
# => curl -X POST 'http://httpbin.org/post?a=123&b=hoge' -d '@body.json' -H 'X-Hoge: myheader' -H 'Content-Type: application/json'  -v  -s 

CurlBuilder#execはコマンドラインを組み立ててそれを実行する。コマンドライン、標準エラー出力、標準出力をそれぞれ色分けして表示してくれるのが少し便利なところ。

c.exec(base_url: "http://httpbin.org/post", method: "POST", params: {a: 123, b: "hoge"}, headers: {"X-Hoge": "myheader", "Content-Type": "application/json"}, body_filename: "body.json")

Faradayを使う方法

faraday_curlというFaradayのアダプタを使うと、Faradayのインターフェイスを使って書いたコードからcurlコマンドを出力できる。

$ gem install faraday
$ gem install faraday_curl
require 'faraday_curl'
require 'logger'

domain = "http://httpbin.org/"
logger = Logger.new(nil)

conn =  Faraday.new(:url => domain) do |f|
  f.request :url_encoded
  f.request :curl, logger, :warn
  f.adapter Faraday.default_adapter
end

response = conn.get do |req|
  req.url "/get"
  req.headers['Authorization'] = auth if @use_get_token
end

p response.env[:curl_command]
# => ["curl", "-v", "-X GET", "-H 'User-Agent: Faraday v0.14.0'", "\"http://httpbin.org/get\""]```
9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8