Class: Net::HTTP

Inherits:
Object
  • Object
show all
Defined in:
lib/curler/nethttp.rb

Constant Summary collapse

@@logfile =
nil

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.curl_log(path) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
# File 'lib/curler/nethttp.rb', line 6

def self.curl_log(path)
  if path.is_a? String
    @@logfile = File.open(path, 'at')
  elsif path.is_a? IO
    @@logfile = path
  elsif path.nil?
    @@logfile = nil
  else
    raise AttributeError.new('Invalid value for path')
  end
end

Instance Method Details

#old_requestObject

Monkey-patch the request method



20
# File 'lib/curler/nethttp.rb', line 20

alias_method :old_request, :request

#request(req, body = nil, &block) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/curler/nethttp.rb', line 22

def request(req, body=nil, &block)
  # Need to make the request in order to set some useful stuff in the
  # request object
  unless started?
    start {
      req['connection'] ||= 'close'
      res = old_request(req, body, &block)
    }
  else
    res = old_request(req, body, &block)
  end


  if @@logfile
    if use_ssl?
      url = "https://#{address}"

      if port != 443
        url += ":#{port}"
      end
    else
      url = "http://#{address}"

      if port != 80
        url += ":#{port}"
      end
    end
    url += "#{req.path}"

    method = "-X #{req.method.upcase}"

    headers = []
    req.each_capitalized do |key, value|
      headers << "-H \"#{key}: #{value}\""
    end

    if req.request_body_permitted?
      data = "-d \"#{req.body}\""
    else
      data = ''
    end

    output = ['curl', method, headers.join(' '), data, url].reject(&:empty?)

    @@logfile << (output.join(' ') + "\n")
  end

  return res
end