Module: ServerSide::HTTP::Static

Defined in:
lib/serverside/http/static.rb

Constant Summary collapse

MIME_TYPES =
{
  :php => 'text/html'.freeze,
  :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
@@static_root =
Dir.pwd

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.static_rootObject



22
23
24
# File 'lib/serverside/http/static.rb', line 22

def self.static_root
  @@static_root
end

.static_root=(dir) ⇒ Object



26
27
28
# File 'lib/serverside/http/static.rb', line 26

def self.static_root=(dir)
  @@static_root = dir
end

Instance Method Details

#serve_static(fn) ⇒ Object

Serves a static file or directory.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/serverside/http/static.rb', line 33

def serve_static(fn)
  full_path = @@static_root/fn
  
  if fn =~ INVALID_PATH_RE
    raise BadRequestError, "Invalid path specified (#{fn})"
  elsif !File.exists?(full_path)
    raise NotFoundError, "File not found (#{fn})"
  end
  
  if File.directory?(full_path)
    set_directory_representation(full_path, fn)
  else
    set_file_representation(full_path, fn)
  end
end

#set_directory_representation(full_path, fn) ⇒ Object

Sends a directory representation.



63
64
65
66
67
68
69
70
71
72
# File 'lib/serverside/http/static.rb', line 63

def set_directory_representation(full_path, fn)
  entries = Dir.entries(full_path)
  entries.reject! {|f| f =~ /^\./}
  entries.unshift('..') if fn != '/'
  
  list = entries.map {|e| DIR_LISTING % [fn/e, e]}.join
  html = DIR_TEMPLATE % [fn, fn, list]
  add_header(CONTENT_TYPE, MIME_TYPES[:html])
  @body = html
end

#set_file_representation(full_path, fn) ⇒ Object

Sends a file representation, setting caching-related headers.



50
51
52
53
54
55
56
57
# File 'lib/serverside/http/static.rb', line 50

def set_file_representation(full_path, fn)
  ext = File.extension(full_path)
  ttl = CACHE_TTL[ext]
  validate_cache :etag => File.etag(full_path), :ttl => CACHE_TTL[ext], :last_modified => File.mtime(full_path) do
    add_header(CONTENT_TYPE, MIME_TYPES[ext])
    @body = IO.read(full_path)
  end
end