Class: Cuba::Response

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

Defined Under Namespace

Modules: ContentType

Constant Summary collapse

LOCATION =
"Location".freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(headers = {}) ⇒ Response

Returns a new instance of Response.



25
26
27
28
29
30
# File 'lib/cuba.rb', line 25

def initialize(headers = {})
  @status  = nil
  @headers = headers
  @body    = []
  @length  = 0
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



22
23
24
# File 'lib/cuba.rb', line 22

def body
  @body
end

#headersObject (readonly)

Returns the value of attribute headers.



23
24
25
# File 'lib/cuba.rb', line 23

def headers
  @headers
end

#statusObject

Returns the value of attribute status.



20
21
22
# File 'lib/cuba.rb', line 20

def status
  @status
end

Instance Method Details

#[](key) ⇒ Object



32
33
34
# File 'lib/cuba.rb', line 32

def [](key)
  @headers[key]
end

#[]=(key, value) ⇒ Object



36
37
38
# File 'lib/cuba.rb', line 36

def []=(key, value)
  @headers[key] = value
end


79
80
81
# File 'lib/cuba.rb', line 79

def delete_cookie(key, value = {})
  Rack::Utils.delete_cookie_header!(@headers, key, value)
end

#finishObject



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

def finish
  [@status, @headers, @body]
end

#html(str) ⇒ Object

Write response body as text/html



55
56
57
58
# File 'lib/cuba.rb', line 55

def html(str)
  @headers[Rack::CONTENT_TYPE] = ContentType::HTML
  write(str)
end

#json(str) ⇒ Object

Write response body as application/json



61
62
63
64
# File 'lib/cuba.rb', line 61

def json(str)
  @headers[Rack::CONTENT_TYPE] = ContentType::JSON
  write(str)
end

#redirect(path, status = 302) ⇒ Object



66
67
68
69
# File 'lib/cuba.rb', line 66

def redirect(path, status = 302)
  @headers[LOCATION] = path
  @status  = status
end


75
76
77
# File 'lib/cuba.rb', line 75

def set_cookie(key, value)
  Rack::Utils.set_cookie_header!(@headers, key, value)
end

#text(str) ⇒ Object

Write response body as text/plain



49
50
51
52
# File 'lib/cuba.rb', line 49

def text(str)
  @headers[Rack::CONTENT_TYPE] = ContentType::TEXT
  write(str)
end

#write(str) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/cuba.rb', line 40

def write(str)
  s = str.to_s

  @length += s.bytesize
  @headers[Rack::CONTENT_LENGTH] = @length.to_s
  @body << s
end