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)
|
|
|
|
@at, @root = at.chomp('/'), root.chomp('/')
|
2010-09-29 05:18:31 -04:00
|
|
|
@compiled_at = (Regexp.compile(/^#{Regexp.escape(at)}/) unless @at.blank?)
|
2010-09-03 06:48:21 -04:00
|
|
|
@compiled_root = Regexp.compile(/^#{Regexp.escape(root)}/)
|
|
|
|
@file_server = ::Rack::File.new(root)
|
|
|
|
end
|
2010-07-29 08:12:25 -04:00
|
|
|
|
2010-09-03 06:48:21 -04:00
|
|
|
def match?(path)
|
|
|
|
path = path.dup
|
|
|
|
if @compiled_at.blank? || path.sub!(@compiled_at, '')
|
|
|
|
full_path = 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
|
2010-09-03 17:25:57 -04: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
|