Module: Nut::Response

Defined in:
lib/nut/response.rb

Overview

Response Module

Class Method Summary collapse

Class Method Details

.build_response(response) ⇒ Object

Build Response Constructs a complete Response from a preliminary Response Hash (code, body).

Parameters:

  • response (Hash)

    Preliminary Response Information



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/nut/response.rb', line 24

def self.build_response response

  # Set Response Code
  response[:code] ||= 200

  # Determine Content-Type
  response[:type] = TYPE_SYMBOLS[response[:type]] if response[:type].is_a? Symbol
  response[:type] ||= Typor.data response[:body]

  # Prepare Headers
  response[:headers] = {
    'Server': "#{SERVER_NAME} #{VERSION}",
    'Content-Type': response[:type],
    'Content-Length': response[:body].bytesize
  }

  # Handle Redirects
  if response[:redirect]

    # Allow '301 Moved' permanent redirects (default to '302 Found' Redirects)
    response[:code] = response[:redirect].is_a?(String) ? 301 : (response[:redirect][:permanent] ? 302 : 301)

    # Set Target
    response[:headers]['Location'] = response[:redirect].is_a?(String) ? response[:redirect] : response[:redirect][:to]
  end

  # Compile Response
  compile_response response
end

.compile_response(response) ⇒ Object

Compile Response Sends out an HTTP Response to the Client.

Parameters:

  • response (Hash)

    Response Hash



57
58
59
60
61
# File 'lib/nut/response.rb', line 57

def self.compile_response response
  "HTTP/1.1 #{response[:code]} #{CODES[response[:code]]}\r\n" +
    response[:headers].collect { |k, v| "#{k}: #{v}\r\n" }.join +
    "\r\n" + response[:body]
end