2009-09-26 12:37:42 -04:00
|
|
|
require 'rack/utils'
|
|
|
|
|
|
|
|
module ActionDispatch
|
2010-09-03 06:48:21 -04:00
|
|
|
class FileHandler
|
|
|
|
def initialize(at, root)
|
2011-02-28 21:03:06 -05:00
|
|
|
@at, @root = at.chomp('/'), root.chomp('/')
|
2011-03-01 16:28:59 -05:00
|
|
|
@compiled_at = @at.blank? ? nil : /^#{Regexp.escape(at)}/
|
2011-02-28 21:03:06 -05:00
|
|
|
@compiled_root = /^#{Regexp.escape(root)}/
|
|
|
|
@file_server = ::Rack::File.new(@root)
|
2010-09-03 06:48:21 -04:00
|
|
|
end
|
2010-07-29 08:12:25 -04:00
|
|
|
|
2010-09-03 06:48:21 -04:00
|
|
|
def match?(path)
|
|
|
|
path = path.dup
|
2010-10-04 12:06:04 -04:00
|
|
|
if !@compiled_at || path.sub!(@compiled_at, '')
|
|
|
|
full_path = path.empty? ? @root : File.join(@root, ::Rack::Utils.unescape(path))
|
2010-09-03 17:25:57 -04:00
|
|
|
paths = "#{full_path}#{ext}"
|
2010-09-03 06:48:21 -04:00
|
|
|
|
|
|
|
matches = Dir[paths]
|
|
|
|
match = matches.detect { |m| File.file?(m) }
|
|
|
|
if match
|
|
|
|
match.sub!(@compiled_root, '')
|
|
|
|
match
|
2010-07-29 08:12:25 -04:00
|
|
|
end
|
2010-09-03 06:48:21 -04:00
|
|
|
end
|
|
|
|
end
|
2010-07-29 08:12:25 -04:00
|
|
|
|
2010-09-03 06:48:21 -04:00
|
|
|
def call(env)
|
|
|
|
@file_server.call(env)
|
2010-07-29 08:12:25 -04:00
|
|
|
end
|
2011-02-28 22:47:09 -05:00
|
|
|
|
|
|
|
def ext
|
|
|
|
@ext ||= begin
|
|
|
|
ext = ::ActionController::Base.page_cache_extension
|
|
|
|
"{,#{ext},/index#{ext}}"
|
|
|
|
end
|
|
|
|
end
|
2010-09-03 06:48:21 -04:00
|
|
|
end
|
2010-07-29 08:12:25 -04:00
|
|
|
|
2010-09-03 06:48:21 -04:00
|
|
|
class Static
|
2009-09-26 12:37:42 -04:00
|
|
|
FILE_METHODS = %w(GET HEAD).freeze
|
|
|
|
|
2010-07-29 08:12:25 -04:00
|
|
|
def initialize(app, roots)
|
2009-09-26 12:37:42 -04:00
|
|
|
@app = app
|
2010-09-03 06:48:21 -04:00
|
|
|
@file_handlers = create_file_handlers(roots)
|
2009-09-26 12:37:42 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def call(env)
|
|
|
|
path = env['PATH_INFO'].chomp('/')
|
|
|
|
method = env['REQUEST_METHOD']
|
|
|
|
|
|
|
|
if FILE_METHODS.include?(method)
|
2010-09-03 06:48:21 -04:00
|
|
|
@file_handlers.each do |file_handler|
|
|
|
|
if match = file_handler.match?(path)
|
|
|
|
env["PATH_INFO"] = match
|
2010-07-29 08:12:25 -04:00
|
|
|
return file_handler.call(env)
|
2009-09-26 12:37:42 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
@app.call(env)
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
2010-09-03 06:48:21 -04:00
|
|
|
def create_file_handlers(roots)
|
|
|
|
roots = { '' => roots } unless roots.is_a?(Hash)
|
2009-09-26 12:37:42 -04:00
|
|
|
|
2010-07-29 08:12:25 -04:00
|
|
|
roots.map do |at, root|
|
2010-09-03 06:48:21 -04:00
|
|
|
FileHandler.new(at, root) if File.exist?(root)
|
|
|
|
end.compact
|
2009-09-26 12:37:42 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|