Class: Lennarb::Response

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

Overview

Response object

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeResponse

Initialize the response object



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

def initialize
  @status = 200
  @headers = {}
  @body = []
  @length = 0
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



13
14
15
# File 'lib/lennarb/response.rb', line 13

def body
  @body
end

#headersObject (readonly)

Returns the value of attribute headers.



18
19
20
# File 'lib/lennarb/response.rb', line 18

def headers
  @headers
end

#lengthObject (readonly)

Returns the value of attribute length.



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

def length
  @length
end

#statusInteger

Returns:

  • (Integer)


8
9
10
# File 'lib/lennarb/response.rb', line 8

def status
  @status
end

Instance Method Details

#[](key) ⇒ Object

Set the response header

Parameters:

  • key (String)


53
54
55
# File 'lib/lennarb/response.rb', line 53

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

#[]=(key, value) ⇒ Object

Get the response header

Parameters:

  • key (String)
  • value (String)


64
65
66
# File 'lib/lennarb/response.rb', line 64

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

#finishObject

Finish the response



135
136
137
# File 'lib/lennarb/response.rb', line 135

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

#html(str) ⇒ Object

Set the response type to html

Parameters:

  • str (String)


98
99
100
101
# File 'lib/lennarb/response.rb', line 98

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

#json(str) ⇒ Object

Set the response type to json

Parameters:

  • str (String)


109
110
111
112
113
114
115
116
117
# File 'lib/lennarb/response.rb', line 109

def json(str)
  json_str = JSON.generate(str)
  @headers[CONTENT_TYPE] = Lennarb::CONTENT_TYPE[:JSON]
  write(json_str)
rescue JSON::GeneratorError => e
  @status = 500
  @headers[CONTENT_TYPE] = Lennarb::CONTENT_TYPE[:TEXT]
  write("JSON generation error: #{e.message}")
end

#redirect(path, status = 302) ⇒ Object

Redirect the response

Parameters:

  • path (String)
  • status, (Integer)

    default: 302



124
125
126
127
128
129
# File 'lib/lennarb/response.rb', line 124

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

  throw :halt, finish
end

#text(str) ⇒ Object

Set the response type to text

Parameters:

  • str (String)


87
88
89
90
# File 'lib/lennarb/response.rb', line 87

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

#write(str) ⇒ Object

Write to the response body

Parameters:

  • str (String)


74
75
76
77
78
79
# File 'lib/lennarb/response.rb', line 74

def write(str)
  str = str.to_s
  @length += str.bytesize
  @headers[CONTENT_LENGTH] = @length.to_s
  @body << str
end