Module ServerSide::HTTP::Static
In: lib/serverside/http/static.rb

Methods

Constants

MIME_TYPES = { :html => 'text/html'.freeze, :css => 'text/css'.freeze, :js => 'text/javascript'.freeze, :gif => 'image/gif'.freeze, :jpg => 'image/jpeg'.freeze, :jpeg => 'image/jpeg'.freeze, :png => 'image/png'.freeze, :ico => 'image/x-icon'.freeze
CACHE_TTL = {}
INVALID_PATH_RE = /\.\./.freeze
DIR_TEMPLATE = '<html><head><title>Directory Listing for %s</title></head><body><h2>Directory listing for %s:</h2><ul>%s</ul></body></html>'.freeze
DIR_LISTING = '<li><a href="%s">%s</a><br/></li>'.freeze

Public Class methods

[Source]

    # File lib/serverside/http/static.rb, line 21
21:     def self.static_root
22:       @@static_root
23:     end

[Source]

    # File lib/serverside/http/static.rb, line 25
25:     def self.static_root=(dir)
26:       @@static_root = dir
27:     end

Public Instance methods

Serves a static file or directory.

[Source]

    # File lib/serverside/http/static.rb, line 32
32:     def serve_static(fn)
33:       full_path = @@static_root/fn
34:       
35:       if fn =~ INVALID_PATH_RE
36:         raise BadRequestError, "Invalid path specified (#{fn})"
37:       elsif !File.exists?(full_path)
38:         raise NotFoundError, "File not found (#{fn})"
39:       end
40:       
41:       if File.directory?(full_path)
42:         set_directory_representation(full_path, fn)
43:       else
44:         set_file_representation(full_path, fn)
45:       end
46:     end

Sends a directory representation.

[Source]

    # File lib/serverside/http/static.rb, line 62
62:     def set_directory_representation(full_path, fn)
63:       entries = Dir.entries(full_path)
64:       entries.reject! {|f| f =~ /^\./}
65:       entries.unshift('..') if fn != '/'
66:       
67:       list = entries.map {|e| DIR_LISTING % [fn/e, e]}.join
68:       html = DIR_TEMPLATE % [fn, fn, list]
69:       add_header(CONTENT_TYPE, MIME_TYPES[:html])
70:       @body = html
71:     end

Sends a file representation, setting caching-related headers.

[Source]

    # File lib/serverside/http/static.rb, line 49
49:     def set_file_representation(full_path, fn)
50:       ext = File.extension(full_path)
51:       ttl = CACHE_TTL[ext]
52:       validate_cache :etag => File.etag(full_path), :ttl => CACHE_TTL[ext], :last_modified => File.mtime(full_path) do
53:         add_header(CONTENT_TYPE, MIME_TYPES[ext])
54:         @body = IO.read(full_path)
55:       end
56:     end

[Validate]