Class: Webmachine::Adapters::Mongrel::Handler

Inherits:
Mongrel::HttpHandler
  • Object
show all
Defined in:
lib/webmachine/adapters/mongrel.rb

Overview

A Mongrel handler for Webmachine

Instance Method Summary collapse

Constructor Details

#initialize(application) ⇒ Handler


39
40
41
42
# File 'lib/webmachine/adapters/mongrel.rb', line 39

def initialize(application)
  @application = application
  super()
end

Instance Method Details

#process(wreq, wres) ⇒ Object

Processes an individual request from Mongrel through Webmachine.


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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/webmachine/adapters/mongrel.rb', line 45

def process(wreq, wres)
  header = Webmachine::Headers.from_cgi(wreq.params)

  request = Webmachine::Request.new(wreq.params["REQUEST_METHOD"],
                                    URI.parse(wreq.params["REQUEST_URI"]),
                                    header,
                                    RequestBody.new(wreq))

  response = Webmachine::Response.new
  @application.dispatcher.dispatch(request, response)

  begin
    wres.status = response.code.to_i
    wres.send_status(nil)

    response.headers.each do |k, vs|
      [*vs].each do |v|
        wres.header[k] = v
      end
    end

    wres.header['Server'] = [Webmachine::SERVER_STRING, "Mongrel/#{::Mongrel::Const::MONGREL_VERSION}"].join(" ")
    wres.send_header

    case response.body
    when String
      wres.write response.body
      wres.socket.flush
    when Enumerable
      # This might be an IOEncoder with a Content-Length, which shouldn't be chunked.
      if response.headers["Transfer-Encoding"] == "chunked"
        Webmachine::ChunkedBody.new(response.body).each do |part|
          wres.write part
          wres.socket.flush
        end
      else
        response.body.each do |part|
          wres.write part
          wres.socket.flush
        end
      end
    else
      if response.body.respond_to?(:call)
        Webmachine::ChunkedBody.new(Array(response.body.call)).each do |part|
          wres.write part
          wres.socket.flush
        end
      end
    end
  ensure
    response.body.close if response.body.respond_to? :close
  end
end