Class: Adsf::Rack::IndexFileFinder

Inherits:
Object
  • Object
show all
Defined in:
lib/adsf/rack/index_file_finder.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, root:, index_filenames: ['index.html']) ⇒ IndexFileFinder

Returns a new instance of IndexFileFinder.



5
6
7
8
9
# File 'lib/adsf/rack/index_file_finder.rb', line 5

def initialize(app, root:, index_filenames: ['index.html'])
  @app = app
  @root = root
  @index_filenames = index_filenames
end

Instance Method Details

#call(env) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/adsf/rack/index_file_finder.rb', line 11

def call(env)
  # Get path
  path_info = ::Rack::Utils.unescape(env['PATH_INFO'])
  path = ::File.join(@root, path_info)

  # Redirect if necessary
  if ::File.directory?(path) && path_info !~ %r{/$}
    new_path_info = env['PATH_INFO'] + '/'
    return [
      302,
      { 'location' => new_path_info, 'content-type' => 'text/html' },
      ["Redirecting you to #{new_path_info}…"],
    ]
  end

  # Add index file if necessary
  new_env = env.dup
  if ::File.directory?(path)
    index_filename = index_file_in(path)
    if index_filename
      new_env['PATH_INFO'] = ::File.join(path_info, index_filename)
    end
  end

  # Pass on
  @app.call(new_env)
end