Class: RackDirect::DirectHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/rack_direct/direct_handler.rb

Class Method Summary collapse

Class Method Details

.run(app, options = nil) ⇒ Object



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
# File 'lib/rack_direct/direct_handler.rb', line 6

def self.run(app, options=nil)
  @@verbose = options[:verbose]
  request = []
  while true
    line = STDIN.gets
    if line.blank?
      begin
        break if request[0] == "EXIT" || request[0].blank?
        payload = JSON.parse request[0]
        uri = payload["uri"]

        #
        # Fix up names in the hash to match what MockRequest is looking for
        payload[:input] = payload["body"]
        payload[:method] = payload["method"]
        payload[:params] = payload["params"]

        rack_env = Rack::MockRequest.env_for(uri, payload)
        rack_env["rack.errors"] = STDERR

        self.serve app, rack_env

      rescue => e
        STDERR.puts "Exception: #{e}"
        e.backtrace.each { |x| STDERR.puts x }
      ensure
        request = []
      end
    else
      request << line.strip
    end
  end
end

.send_body(body, file = STDOUT) ⇒ Object



93
94
95
96
97
98
# File 'lib/rack_direct/direct_handler.rb', line 93

def self.send_body(body, file = STDOUT)
  body.each { |part|
    file.print part
    file.flush
  }
end

.send_headers(status, headers, file = STDOUT) ⇒ Object



82
83
84
85
86
87
88
89
90
91
# File 'lib/rack_direct/direct_handler.rb', line 82

def self.send_headers(status, headers, file = STDOUT)
  file.print "Status: #{status}\r\n"
  headers.each { |k, vs|
    vs.each { |v|
      file.print "#{k}: #{v}\r\n"
    }
  }
  file.print "\r\n"
  file.flush
end

.serve(app, env) ⇒ Object



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
71
72
73
74
75
76
77
78
79
80
# File 'lib/rack_direct/direct_handler.rb', line 40

def self.serve(app, env)
  if @@verbose
    STDERR.puts "Calling serve"
    STDERR.puts("Rack env:")
    $> = STDERR
    pp rack_env
    $> = STDOUT
    STDERR.puts("Body: #{rack_env["rack.input"].string}")
  end

  status, headers, body = app.call(env)

  begin
    body_string = ""
    body.each { |part| body_string += part }
    result = {
      "status" => status,
      "headers" => headers,
      "body" => body_string
    }

    if @@verbose
      STDERR.puts "Sending result (#{status})"
      STDERR.puts result.to_json
    end

    unique_id = env["direct_request.unique_id"]

    STDOUT.puts "BEGIN #{unique_id}"
    STDOUT.puts result.to_json
    STDOUT.puts "END #{unique_id}"
    STDOUT.flush

    if @@verbose
      send_headers status, headers, STDERR
      send_body body, STDERR
    end
  ensure
    body.close  if body.respond_to? :close
  end
end