File: index_file_finder.rb

package info (click to toggle)
ruby-adsf 1.2.1%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 140 kB
  • ctags: 30
  • sloc: ruby: 185; makefile: 11
file content (48 lines) | stat: -rw-r--r-- 1,186 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
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
38
39
40
41
42
43
44
45
46
47
48
module Adsf::Rack

  class IndexFileFinder

    def initialize(app, options)
      @app = app
      @root = options[:root] or raise ArgumentError, ':root option is required but was not given'
      @index_filenames = options[:index_filenames] || [ 'index.html' ]
    end

    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 !~ /\/$/
        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)
        if index_filename = index_file_in(path)
          new_env['PATH_INFO'] = ::File.join(path_info, index_filename)
        end
      end

      # Pass on
      @app.call(new_env)
    end

  private

    def index_file_in(dir)
      @index_filenames.find do |index_filename|
        ::File.file?(::File.join(dir, index_filename))
      end
    end

  end

end