Class: Diode::Response

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

Constant Summary collapse

STATUS =
{
  200 => "OK",
  400 => "Bad Request",
  403 => "Forbidden",
  404 => "Not Found",
  405 => "Method Not Allowed"
}
DEFAULT_HEADERS =
{
  "Content-Type" => "application/json",
  "Date" => Time.now.httpdate(),
  "Cache-Control" => "no-store",
  "Server" => "Diode/1.0",
  "Connection" => "Keep-Alive"
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(code, body = "", headers = {}) ⇒ Response

Returns a new instance of Response.



40
41
42
43
44
# File 'lib/diode/response.rb', line 40

def initialize(code, body="", headers={})
  @code = code.to_i()
  @body = body
  @headers = DEFAULT_HEADERS.merge(headers)
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



38
39
40
# File 'lib/diode/response.rb', line 38

def body
  @body
end

#codeObject

Returns the value of attribute code.



38
39
40
# File 'lib/diode/response.rb', line 38

def code
  @code
end

#headersObject

Returns the value of attribute headers.



38
39
40
# File 'lib/diode/response.rb', line 38

def headers
  @headers
end

Class Method Details

.standard(code) ⇒ Object

returns the html for a few status codes



24
25
26
27
28
29
30
# File 'lib/diode/response.rb', line 24

def self.standard(code)
  raise("code #{code} is not supported") unless STATUS.key?(code)
  message = STATUS[code]
  body = "<html><head><title>#{message}</title></head><body><h1>#{code} - #{message}</h1></body></html>\n"
  h = DEFAULT_HEADERS.merge({"Content-Type" => "text/html"})
  new(code, body, h)
end

.xml(code, body = "", headers = {}) ⇒ Object



32
33
34
35
36
# File 'lib/diode/response.rb', line 32

def self.xml(code, body="", headers={})
  resp = Response.new(code, body, headers)
  resp.headers["Content-Type"] = "application/xml"
  return resp
end

Instance Method Details

#to_sObject

return the response as a raw HTTP string



47
48
49
50
51
52
53
54
# File 'lib/diode/response.rb', line 47

def to_s()
  @headers["Content-Length"] = @body.bytes.size() unless @body.empty?
  msg = ["HTTP/1.1 #{@code} #{STATUS[@code]}"]
  @headers.keys.each { |k|
    msg << "#{k}: #{@headers[k]}"
  }
  msg.join("\r\n") + "\r\n\r\n" + @body
end