Skip to content

Instantly share code, notes, and snippets.

@mat
Created July 18, 2014 16:46
Show Gist options
  • Save mat/983b1f8ec900b61cc84e to your computer and use it in GitHub Desktop.
Save mat/983b1f8ec900b61cc84e to your computer and use it in GitHub Desktop.
Typhoeus request to curl command string.
#
# Generate curl command from a Typhoeus request.
#
# Example:
#
# > request = Typhoeus::Request.post("http://example.com", {body: "fine stuff"}).request
# > TyphoeusToCurl.new.to_curl(request)
#
# => "curl 'http://example.com' -X POST -H \"User-Agent: Typhoeus" -d 'fine stuff' --compressed"
#
class TyphoeusToCurl
def to_curl(typhoeus_request)
url = "'#{typhoeus_request.url}'"
method = method(typhoeus_request)
headers = headers(typhoeus_request)
data = data(typhoeus_request)
["curl", url, method, headers, data, "--compressed"].compact.join(" ")
end
private
# -X PUT
def method(request)
if request.method.to_s == "get"
return nil
end
"-X #{request.method.to_s.upcase}"
end
# -H "Accept-Encoding: deflate, gzip"
def headers(request)
if request.headers.empty?
return nil
end
request.headers.map { |key, value|
%Q(-H "#{key}: #{value}")
}
end
# -d 'data....'
def data(request)
if request.body.nil?
return nil
end
"-d '#{request.body}'"
end
end
@silva96
Copy link

silva96 commented Jun 15, 2017

def method(request)
    if request.options[:method].to_s == "get"
      return nil
    end

    "-X #{equest.options[:method].to_s.upcase}"
  end


def headers(request)
    if request.options[:headers].empty?
      return nil
    end

    request.options[:headers].map { |key, value|
      %Q(-H "#{key}: #{value}")
    }
  end

def data(request)
    if request.options[:body].nil?
      return nil
    end

    "-d '#{request.options[:body]}'"
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment