Class: Response

Inherits:
Object
  • Object
show all
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

Class Method Summary collapse

Instance Method Summary collapse

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

#bodyObject (readonly)

Returns the value of attribute body.



4
5
6
# File 'lib/response.rb', line 4

def body
  @body
end

#headerObject (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

#streamObject



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

def stream
  File.read(self.body)
end