Class: Webmachine::Adapters::Rack

Inherits:
Webmachine::Adapter show all
Defined in:
lib/webmachine/adapters/rack.rb

Overview

A minimal “shim” adapter to allow Webmachine to interface with Rack. The intention here is to allow Webmachine to run under Rack-compatible web-servers, like unicorn and pow, and is not intended to allow Webmachine to be “plugged in” to an existing Rack app as middleware.

To use this adapter, create a config.ru file and populate it like so:

require 'webmachine/adapters/rack'

# put your own Webmachine resources in another file:
require 'my/resources'

run MyApplication.adapter

Servers like pow and unicorn will read config.ru by default and it should all “just work”.

And for development or testing your application can be run with Rack’s builtin Server identically to the Mongrel and WEBrick adapters with:

MyApplication.run

Defined Under Namespace

Classes: RequestBody

Instance Attribute Summary

Attributes inherited from Webmachine::Adapter

#configuration, #dispatcher

Instance Method Summary collapse

Methods inherited from Webmachine::Adapter

#initialize, run

Constructor Details

This class inherits a constructor from Webmachine::Adapter

Instance Method Details

#call(env) ⇒ Object

Handles a Rack-based request.

Parameters:

  • env (Hash)

    the Rack environment



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
# File 'lib/webmachine/adapters/rack.rb', line 48

def call(env)
  headers = Webmachine::Headers.from_cgi(env)

  rack_req = ::Rack::Request.new env
  request = Webmachine::Request.new(rack_req.request_method,
                                    URI.parse(rack_req.url),
                                    headers,
                                    RequestBody.new(rack_req))

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

  response.headers['Server'] = [Webmachine::SERVER_STRING, "Rack/#{::Rack.version}"].join(" ")

  rack_status = response.code
  rack_headers = response.headers.flattened("\n")
  rack_body = case response.body
              when String # Strings are enumerable in ruby 1.8
                [response.body]
              else
                if response.body.respond_to?(:call)
                  Webmachine::ChunkedBody.new(Array(response.body.call))
                elsif response.body.respond_to?(:each)
                  Webmachine::ChunkedBody.new(response.body)
                else
                  [response.body.to_s]
                end
              end

  rack_res = ::Rack::Response.new(rack_body, rack_status, rack_headers)
  rack_res.finish
end

#runObject

Start the Rack adapter



36
37
38
39
40
41
42
43
44
# File 'lib/webmachine/adapters/rack.rb', line 36

def run
  options = {
    :app => self,
    :Port => configuration.port,
    :Host => configuration.ip
  }.merge(configuration.adapter_options)

  ::Rack::Server.start(options)
end