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
# File 'lib/nut/response.rb', line 24

def self.build_response response

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

	# Ensure Body is present
	response[:body] = '0' unless response[:body].nstr

	# Determine Content-Type
	response[:type] = TYPE_SYMBOLS[response[:type]] if response[:type].is_a? Symbol
	response[:type] ||= Typor.data(response[:body]) || 'text/html'

	# Prepare Headers
	response[:headers].merge! '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) ? 302 : (response[:redirect][:permanent] ? 301 : 302)

		# 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



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

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