Class: Rack::App::FileServer

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/app/file_server.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root_folder) ⇒ FileServer

Returns a new instance of FileServer.



3
4
5
6
7
8
# File 'lib/rack/app/file_server.rb', line 3

def initialize(root_folder)
  require 'rack/file'
  @root_folder = root_folder
  @relative_file_paths = Dir.glob(File.join(@root_folder, '**', '*')).map { |file_path| file_path.sub(@root_folder, '') }.sort_by { |str| str.length }.reverse
  @rack_file_server = ::Rack::File.new(@root_folder, {})
end

Class Method Details

.serve_file(env, file_path) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/rack/app/file_server.rb', line 23

def self.serve_file(env, file_path)
  file_server = self.new(File.dirname(file_path))
  env = env.dup
  env[::Rack::App::Constants::ENV::REQUEST_METHOD]= 'GET'
  env[::Rack::App::Constants::ENV::PATH_INFO]= file_path
  file_server.call(env)
end

Instance Method Details

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/rack/app/file_server.rb', line 10

def call(env)
  path_info = clean_path_info(env)

  @relative_file_paths.each do |relative_file_path|
    if path_info =~ /#{Regexp.escape(relative_file_path)}$/
      env[::Rack::App::Constants::ENV::PATH_INFO]= relative_file_path
      break
    end
  end

  @rack_file_server.call(env)
end