Class: Troy::Server
- Inherits:
-
Object
- Object
- Troy::Server
- Defined in:
- lib/troy/server.rb
Instance Attribute Summary collapse
-
#request ⇒ Object
readonly
Returns the value of attribute request.
-
#root ⇒ Object
readonly
Returns the value of attribute root.
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(root) ⇒ Server
constructor
A new instance of Server.
- #normalized_path ⇒ Object
- #process ⇒ Object
- #redirect(path) ⇒ Object
- #render(status, content_type, path) ⇒ Object
Constructor Details
Instance Attribute Details
#request ⇒ Object (readonly)
Returns the value of attribute request.
5 6 7 |
# File 'lib/troy/server.rb', line 5 def request @request end |
#root ⇒ Object (readonly)
Returns the value of attribute root.
5 6 7 |
# File 'lib/troy/server.rb', line 5 def root @root end |
Instance Method Details
#call(env) ⇒ Object
11 12 13 14 |
# File 'lib/troy/server.rb', line 11 def call(env) @request = Rack::Request.new(env) process end |
#normalized_path ⇒ Object
32 33 34 35 36 |
# File 'lib/troy/server.rb', line 32 def normalized_path path = request.path.gsub(%r{/$}, "") path << "?#{request.query_string}" unless request.query_string.empty? path end |
#process ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/troy/server.rb', line 42 def process path = request.path[%r{^/(.*?)/?$}, 1] path = "index" if path == "" path = root.join(path) if request.path != "/" && request.path.end_with?("/") redirect normalized_path elsif (file_path = Pathname.new("#{path}.html")).file? render(200, "text/html; charset=utf-8", file_path) elsif (file_path = Pathname.new("#{path}.xml")).file? render(200, "text/xml; charset=utf-8", file_path) elsif path.file? render(200, Rack::Mime.mime_type(path.extname, "text/plain"), path) else render(404, "text/html; charset=utf-8", root.join("404.html")) end rescue StandardError render(500, "text/html; charset=utf-8", root.join("500.html")) end |
#redirect(path) ⇒ Object
38 39 40 |
# File 'lib/troy/server.rb', line 38 def redirect(path) [301, {"Content-Type" => "text/html", "Location" => path}, []] end |
#render(status, content_type, path) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/troy/server.rb', line 16 def render(status, content_type, path) last_modified = path.mtime.httpdate if request.env["HTTP_IF_MODIFIED_SINCE"] == last_modified return [304, {}, []] end headers = { "Content-Type" => content_type, "Last-Modified" => last_modified } content = request.head? ? [] : [path.read] [status, headers, content] end |