Class: Guaraci::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/guaraci/response.rb

Overview

HTTP response builder for the Guaraci web framework.

It handles the conversion between high-level Ruby objects and the low-level Protocol::HTTP objects required by the HTTP server.

Examples:

Basic JSON response

response = Guaraci::Response.ok do |res|
  res.json({ message: "Hello World", status: "success" })
end
response.render #=> Protocol::HTTP::Response

HTML response with custom status

response = Guaraci::Response.new(201) do |res|
  res.html("<h1>Resource Created</h1>")
end
response.render

Plain text response

response = Guaraci::Response.ok do |res|
  res.text("Simple message")
end
response.render

See Also:

Author:

  • Guilherme SIlva

Since:

  • 1.0.0

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(status) ⇒ Response

Initialize a new HTTP response with the specified status code.

Creates a new response instance with empty headers and body. The headers are initialized as Protocol::HTTP::Headers and the body starts as an empty buffered body until content is written.

Examples:

Creating different response types

success = Guaraci::Response.new(200)    # OK
not_found = Guaraci::Response.new(404)  # Not Found
error = Guaraci::Response.new(500)      # Internal Server Error

With content

response = Guaraci::Response.new(201)
response.json({ id: 123, created: true })

Parameters:

  • status (Integer)

    HTTP status code

Raises:

  • (ArgumentError)

    if status is not a valid HTTP status code

Since:

  • 1.0.0



90
91
92
93
94
# File 'lib/guaraci/response.rb', line 90

def initialize(status)
  @status = status
  @headers = Protocol::HTTP::Headers.new
  @body = default_body
end

Instance Attribute Details

#bodyProtocol::HTTP::Body::Buffered (readonly)

The HTTP response body containing the actual content.

The body is automatically converted to Protocol::HTTP::Body::Buffered format when content is written using #write, #json, #html, or #text. This ensures compatibility with Async::HTTP’s streaming requirements.

Examples:

response.body.read #=> '{"message":"Hello World"}'

Returns:

  • (Protocol::HTTP::Body::Buffered)

    HTTP response body

See Also:

Since:

  • 1.0.0



60
61
62
# File 'lib/guaraci/response.rb', line 60

def body
  @body
end

#headersProtocol::HTTP::Headers (readonly)

The HTTP response headers collection.

Headers are stored as Protocol::HTTP::Headers objects

Examples:

response.headers['content-type'] #=> 'application/json'
response.headers['content-length'] #=> '25'

Returns:

  • (Protocol::HTTP::Headers)

    HTTP response headers

See Also:

Since:

  • 1.0.0



71
72
73
# File 'lib/guaraci/response.rb', line 71

def headers
  @headers
end

#statusInteger (readonly)

The HTTP status code for this response.

Common status codes:

  • 200: OK (successful request)

  • 201: Created (resource created successfully)

  • 400: Bad Request (client error)

  • 404: Not Found (resource not found)

  • 500: Internal Server Error (server error)

Examples:

response.status #=> 200

Returns:

  • (Integer)

    HTTP status code (e.g., 200, 404, 500)

See Also:

Since:

  • 1.0.0



48
49
50
# File 'lib/guaraci/response.rb', line 48

def status
  @status
end

Class Method Details

.ok {|response| ... } ⇒ Response

Create a successful HTTP response (200 OK).

This is a convenient factory method for creating successful responses. It automatically sets the status to 200 and yields the response instance to the provided block for content configuration.

Examples:

Without block (empty 200 response)

response = Guaraci::Response.ok
response.status #=> 200

With configuration block

response = Guaraci::Response.ok do |res|
  res.json({ message: "Operation successful!" })
end

Method chaining after creation

response = Guaraci::Response.ok
response.json({ data: [1, 2, 3] })

Yields:

  • (response)

    Block to configure the response content and headers

Yield Parameters:

  • response (Response)

    The response instance to configure

Returns:

  • (Response)

    The configured response instance with status 200

Since:

  • 1.0.0



118
119
120
121
122
# File 'lib/guaraci/response.rb', line 118

def self.ok
  res = new(200)
  yield(res) if block_given?
  res
end

Instance Method Details

#html(content) ⇒ Response

Write HTML content to the response body.

Sets the Content-Type to “text/html” and writes the provided HTML string. No HTML validation or processing is performed - the content is sent as-is.

Examples:

Simple HTML

response.html("<h1>Welcome</h1>")

Complete HTML document

response.html(<<~HTML)
  <!DOCTYPE html>
  <html>
    <head><title>My Page</title></head>
    <body><h1>Hello World!</h1></body>
  </html>
HTML

Parameters:

  • content (String)

    HTML content

Returns:

  • (Response)

    Self for method chaining

Since:

  • 1.0.0



173
174
175
# File 'lib/guaraci/response.rb', line 173

def html(content)
  write(content, content_type: "text/html")
end

#json(content) ⇒ Response

Write JSON content to the response body.

Automatically serializes the provided object to JSON using JSON.dump

Examples:

Hash object

response.json({ message: "Hello", data: [1, 2, 3] })

Parameters:

  • content (Object)

    Any object that can be serialized to JSON

Returns:

  • (Response)

    Self for method chaining

Since:

  • 1.0.0



150
151
152
# File 'lib/guaraci/response.rb', line 150

def json(content)
  write(JSON.dump(content))
end

#renderProtocol::HTTP::Response

Convert the response to a Protocol::HTTP::Response object.

This method transforms the Guaraci::Response into the low-level response format required by the Async::HTTP server. It ensures that all components (status, headers, body) are properly formatted for HTTP transmission.

The returned object contains:

  • version: HTTP version (automatically determined by Protocol::HTTP)

  • status: Integer HTTP status code

  • headers: Protocol::HTTP::Headers instance with all response headers

  • body: Protocol::HTTP::Body::Buffered instance containing the response content

Examples:

Basic usage

response = Guaraci::Response.ok { |r| r.json({message: "Hello"}) }
http_response = response.render
http_response.status #=> 200
http_response.headers['content-type'] #=> 'application/json'

Returns:

  • (Protocol::HTTP::Response)

    A complete HTTP response object ready for transmission

See Also:

Since:

  • 1.0.0



214
215
216
# File 'lib/guaraci/response.rb', line 214

def render
  Protocol::HTTP::Response.new(nil, @status, @headers, @body)
end

#text(content) ⇒ Response

Write plain text content to the response body.

Sets the Content-Type to “text/plain” and writes the provided text.

Examples:

Simple text

response.text("Hello, World!")

Multi-line text

response.text("Line 1\nLine 2\nLine 3")

Parameters:

  • content (String)

    Plain text content

Returns:

  • (Response)

    Self for method chaining

Since:

  • 1.0.0



189
190
191
# File 'lib/guaraci/response.rb', line 189

def text(content)
  write(content, content_type: "text/plain")
end

#write(content, content_type: "application/json") ⇒ Response

Write content to the response body with specified content type.

This is the base method used by all other content methods (json, html, text). It automatically converts the content to Protocol::HTTP::Body::Buffered format required by Async::HTTP and sets the appropriate Content-Type header.

Parameters:

  • content (String, Array)

    Content to write to response body

  • content_type (String) (defaults to: "application/json")

    MIME type for the response

Returns:

  • (Response)

    Self for method chaining

See Also:

  • Protocol::HTTP::Body::Buffered

Since:

  • 1.0.0



135
136
137
138
139
# File 'lib/guaraci/response.rb', line 135

def write(content, content_type: "application/json")
  @headers["content-type"] = content_type
  @body = Protocol::HTTP::Body::Buffered.wrap(content)
  self
end