Module: RackCurler

Defined in:
lib/rack_curler.rb,
lib/rack_curler/version.rb

Constant Summary collapse

VERSION =
"0.0.2"

Class Method Summary collapse

Class Method Details

.to_curl(env, options = {}) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rack_curler.rb', line 4

def self.to_curl(env, options={})

  headers_to_drop = [
    'Version',         # make your life easy and let curl set this
    'Content-Length',  # curl will set this for you
    'Host',            # curl will set this for you
    'Connection',      # curl will set this for you
    'Accept-Encoding', # for debugging, you don't want an encoded-response
    'Date'             # it would be incorrect to repeat
  ]

  header_defaults = {
    'Accept' => '*/*',
    'Content-Type' => 'application/x-www-form-urlencoded'
  }
  
  env['rack.input'].rewind
  body = env['rack.input'].read
  env['rack.input'].rewind

  headerize = lambda { |raw| raw.split(/[ _\-]/).map(&:capitalize).join('-') }

  headers = {}.tap do |h|
    env.select { |k, v| k =~ /^HTTP_/ || k == 'CONTENT_TYPE' }
      .each { |k, v| h[headerize.call(k.sub(/^HTTP_/, ''))] = v}
    h.select! { |k, v| !headers_to_drop.member?(k) }
    h.select! { |k, v| header_defaults[k].nil? || header_defaults[k] != v }
  end
  
  url = Rack::Request.new(env).url

  line_prefix = options[:pretty] ? " \\\n   " : ' '

  curl_command = "curl '#{url}'"
  curl_command << line_prefix << "-X #{env['REQUEST_METHOD']}" unless ['GET', 'POST'].member?(env['REQUEST_METHOD'])
  headers.each_pair do |header, value|
    curl_command << line_prefix << "-H '#{header}: #{value}'"
  end
  curl_command << line_prefix << "--data '#{body}'" if body && !body.empty?

  curl_command
end