Class: Troy::Server

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ Server

Returns a new instance of Server.



7
8
9
# File 'lib/troy/server.rb', line 7

def initialize(root)
  @root = Pathname.new(root)
end

Instance Attribute Details

#requestObject (readonly)

Returns the value of attribute request.



5
6
7
# File 'lib/troy/server.rb', line 5

def request
  @request
end

#rootObject (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_pathObject



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

#processObject



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 (_path = Pathname.new("#{path}.html")).file?
    render(200, "text/html; charset=utf-8", _path)
  elsif (_path = Pathname.new("#{path}.xml")).file?
    render(200, "text/xml; charset=utf-8", _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 Exception => error
  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