Skip to content
This repository has been archived by the owner on Dec 7, 2018. It is now read-only.

Responses

ch1c0t edited this page Sep 24, 2013 · 11 revisions

See also: Reel::Response Yardoc

The Reel::Response class handles sending a response back to a client. You should always send a response by calling the #respond method of a Reel::Request:

connection.each_request do |request|
  request.respond :ok, "hello, world!"
end

This is shorthand for:

connection.each_request do |request|
  request.respond Reel::Response.new(:ok, "hello, world!")
end

Constructing Responses

There are four valid method signatures for constructing a response:

Shorthand (status only)

Reel::Response.new(:ok)

or with an integer status code:

Reel::Response.new(200)

Status and Headers

If the second parameter is a Hash, it will be treated as the response headers:

Reel::Response.new(:found, {Location: "/elsewhere/"})

NOTE: This method allows a streaming body to be supplied after-the-fact. See "Chunked Streaming" section below.

Status and Body

If the second parameter is a String or an Enumerable (which isn't a Hash) it will be treated as the body.

String example:

Reel::Response.new(:ok, "Hello, World")

Enumerable example:

Reel::Response.new(:ok, ["Hello", "World"])

Status, Headers, and Body

You can specify all three as a Symbol/Integer status, Hash of headers, and a String or Enumerable body:

Reel::Response.new(:ok, {"content-type" => "application/json"}, "['mmmkay']")

Chunked Streaming

Reel supports streaming responses using HTTP/1.1's chunked transfer encoding feature.

This is the current API for using this feature:

# Sending transfer_encoding chunked without a body enables streaming mode
request.respond :ok, :transfer_encoding => :chunked

# This will send individual chunks
request << "Hello"
request << "World"
request.finish_response # Write trailer and reset connection to header mode
connection.close

This API is admittedly a bit clunky. It would probably make more sense to write to the response object! If you agree, cruise by https://github.com/celluloid/reel/issues/91

Server-Sent Events

Reel can be used to implement server-sent events, however it does not have built-in support for them. To see how to build them on top of Reel, check out the Server Sent Events Example