Class: Response
- Inherits:
-
Object
- Object
- Response
- Defined in:
- lib/response.rb
Constant Summary collapse
- RESPONSE_CODE =
{ '200' => 'OK', '404' => 'Not Found' }
- CONTENT_TYPE_MAPPING =
{ 'html' => 'text/html', 'txt' => 'text/plain', 'png' => 'image/png', 'jpg' => 'image/jpg' }
- DEFAULT_CONTENT_TYPE =
'application/octet-stream'- NOT_FOUND =
'./public/404.html'
Instance Attribute Summary collapse
-
#body ⇒ Object
readonly
Returns the value of attribute body.
-
#header ⇒ Object
readonly
Returns the value of attribute header.
Class Method Summary collapse
- .build(path) ⇒ Object
- .build_body(path) ⇒ Object
- .build_header(code, type, size) ⇒ Object
- .content_type(path) ⇒ Object
Instance Method Summary collapse
-
#initialize(header, body) ⇒ Response
constructor
A new instance of Response.
- #stream ⇒ Object
Constructor Details
#initialize(header, body) ⇒ Response
Returns a new instance of Response.
6 7 8 9 |
# File 'lib/response.rb', line 6 def initialize(header, body) @header = header @body = body end |
Instance Attribute Details
#body ⇒ Object (readonly)
Returns the value of attribute body.
4 5 6 |
# File 'lib/response.rb', line 4 def body @body end |
#header ⇒ Object (readonly)
Returns the value of attribute header.
4 5 6 |
# File 'lib/response.rb', line 4 def header @header end |
Class Method Details
.build(path) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/response.rb', line 27 def self.build(path) if File.exist?(path) && !File.directory?(path) body, body_size = build_body(path) header = build_header(RESPONSE_CODE.rassoc('OK').join, content_type(path), body_size) Response.new(header, body) else body, body_size = build_body(NOT_FOUND) header = build_header(RESPONSE_CODE.rassoc('Not Found').join, content_type(path), body_size) Response.new(header, body) end end |
.build_body(path) ⇒ Object
55 56 57 58 59 |
# File 'lib/response.rb', line 55 def self.build_body(path) File.open(path, "rb") do |file| return file, file.size end end |
.build_header(code, type, size) ⇒ Object
48 49 50 51 52 53 |
# File 'lib/response.rb', line 48 def self.build_header(code, type, size) "HTTP/1.1 #{code}\r\n" + "Content-Type: #{type}\r\n" + "Content-Length: #{size}\r\n" + "Connection: close\r\n\r\n" end |
.content_type(path) ⇒ Object
43 44 45 46 |
# File 'lib/response.rb', line 43 def self.content_type(path) ext = File.extname(path).split('.').last CONTENT_TYPE_MAPPING.fetch(ext, DEFAULT_CONTENT_TYPE) end |
Instance Method Details
#stream ⇒ Object
61 62 63 |
# File 'lib/response.rb', line 61 def stream File.read(self.body) end |