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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
diff --git a/lib/adsf/rack/index_file_finder.rb b/lib/adsf/rack/index_file_finder.rb
@@ -1,15 +1,16 @@
module Adsf::Rack
class IndexFileFinder
def initialize(app, options)
- @app = app
+ @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
@@ -20,21 +21,28 @@ module Adsf::Rack
{ '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)
- path_to_index = ::File.join(path, 'index.html')
- if ::File.file?(path_to_index)
- new_env['PATH_INFO'] = ::File.join(path_info, 'index.html')
+ 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
diff --git a/test/rack/test_index_file_finder.rb b/test/rack/test_index_file_finder.rb
@@ -1,17 +1,20 @@
require 'test/helper'
class Adsf::Test::Rack::IndexFileFinder < MiniTest::Unit::TestCase
include Rack::Test::Methods
include Adsf::Test::Helpers
def app
- ::Adsf::Rack::IndexFileFinder.new(stub_app, :root => '.')
+ ::Adsf::Rack::IndexFileFinder.new(
+ stub_app,
+ (@options || {}).merge({ :root => '.' })
+ )
end
def stub_app
Rack::File.new('.')
end
def test_get_file
# Create test file
@@ -64,9 +67,24 @@ class Adsf::Test::Rack::IndexFileFinder
File.open('replicants/index.html', 'w') { |io| io.write('Leon, Roy, Pris, Zhora, etc.') }
# Request test directory
get '/replicants/'
assert last_response.ok?
assert_equal 'Leon, Roy, Pris, Zhora, etc.', last_response.body
end
+ def test_get_dir_with_custom_index_file
+ @options = { :index_filenames => [ 'list.xml' ] }
+
+ # Create test directory
+ FileUtils.mkdir('replicants')
+
+ # Create test file
+ File.open('replicants/list.xml', 'w') { |io| io.write('Leon, Roy, Pris, Zhora, etc.') }
+
+ # Request test directory
+ get '/replicants/'
+ assert last_response.ok?
+ assert_equal 'Leon, Roy, Pris, Zhora, etc.', last_response.body
+ end
+
end
|