Class: Simple::Httpd::Rack::StaticMount

Inherits:
Object
  • Object
show all
Defined in:
lib/simple/httpd/rack/static_mount.rb

Overview

A simple file server middleware

Constant Summary collapse

Rack =
::Simple::Httpd::Rack
EXTENSIONS =
%w(.txt .md .js .css .png .jpeg .jpg)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, static_files) ⇒ StaticMount

Returns a new instance of StaticMount.



27
28
29
30
# File 'lib/simple/httpd/rack/static_mount.rb', line 27

def initialize(path, static_files)
  @path = path
  @static_files = Set.new(static_files)
end

Instance Attribute Details

#mount_pointObject (readonly)

Returns the value of attribute mount_point.



25
26
27
# File 'lib/simple/httpd/rack/static_mount.rb', line 25

def mount_point
  @mount_point
end

#pathObject (readonly)

Returns the value of attribute path.



25
26
27
# File 'lib/simple/httpd/rack/static_mount.rb', line 25

def path
  @path
end

Class Method Details

.build(mount_point, path) ⇒ Object



7
8
9
10
11
12
13
14
15
16
# File 'lib/simple/httpd/rack/static_mount.rb', line 7

def self.build(mount_point, path)
  static_files = static_files(path)
  return nil if static_files.empty?

  ::Simple::Httpd.logger.info do
    "#{mount_point}: serving #{static_files.count} static file(s)"
  end

  new(path, static_files)
end

.static_files(path) ⇒ Object



18
19
20
21
22
23
# File 'lib/simple/httpd/rack/static_mount.rb', line 18

def self.static_files(path)
  Dir.chdir(path) do
    pattern = "**/*{" + EXTENSIONS.join(",") + "}"
    Dir.glob(pattern)
  end
end

Instance Method Details

#call(env) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/simple/httpd/rack/static_mount.rb', line 32

def call(env)
  request_path = env["PATH_INFO"]
  if serve_file?(request_path)
    file_path = request_path[1..-1]
    env["PATH_INFO"] = file_path
    file_server.call(env)
  else
    Rack.error 404, "No such file"
  end
end

#file_serverObject



43
44
45
# File 'lib/simple/httpd/rack/static_mount.rb', line 43

def file_server
  @file_server ||= ::Rack::File.new(path)
end

#serve_file?(request_path) ⇒ Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/simple/httpd/rack/static_mount.rb', line 47

def serve_file?(request_path)
  @static_files.include?(request_path[1..-1])
end