2009-09-26 12:37:42 -04:00
|
|
|
require 'rack/utils'
|
2012-02-17 08:33:44 -05:00
|
|
|
require 'active_support/core_ext/uri'
|
2009-09-26 12:37:42 -04:00
|
|
|
|
|
|
|
module ActionDispatch
|
2010-09-03 06:48:21 -04:00
|
|
|
class FileHandler
|
2011-05-03 06:32:14 -04:00
|
|
|
def initialize(root, cache_control)
|
2011-04-15 14:09:39 -04:00
|
|
|
@root = root.chomp('/')
|
2011-02-28 21:03:06 -05:00
|
|
|
@compiled_root = /^#{Regexp.escape(root)}/
|
2013-01-11 16:48:58 -05:00
|
|
|
headers = cache_control && { 'Cache-Control' => cache_control }
|
|
|
|
@file_server = ::Rack::File.new(@root, headers)
|
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
|
|
|
|
|
2012-02-17 08:33:44 -05:00
|
|
|
full_path = path.empty? ? @root : File.join(@root, escape_glob_chars(unescape_path(path)))
|
2011-04-15 14:09:39 -04:00
|
|
|
paths = "#{full_path}#{ext}"
|
|
|
|
|
|
|
|
matches = Dir[paths]
|
|
|
|
match = matches.detect { |m| File.file?(m) }
|
|
|
|
if match
|
|
|
|
match.sub!(@compiled_root, '')
|
2012-02-16 13:50:07 -05:00
|
|
|
::Rack::Utils.escape(match)
|
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
|
2012-10-03 16:35:19 -04:00
|
|
|
ext = ::ActionController::Base.default_static_extension
|
2011-02-28 22:47:09 -05:00
|
|
|
"{,#{ext},/index#{ext}}"
|
|
|
|
end
|
|
|
|
end
|
2012-02-17 08:33:44 -05:00
|
|
|
|
|
|
|
def unescape_path(path)
|
|
|
|
URI.parser.unescape(path)
|
|
|
|
end
|
|
|
|
|
|
|
|
def escape_glob_chars(path)
|
2012-03-08 06:26:10 -05:00
|
|
|
path.force_encoding('binary') if path.respond_to? :force_encoding
|
2012-02-17 09:44:28 -05:00
|
|
|
path.gsub(/[*?{}\[\]]/, "\\\\\\&")
|
2012-02-17 08:33:44 -05:00
|
|
|
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
|
2011-05-03 06:32:14 -04:00
|
|
|
def initialize(app, path, cache_control=nil)
|
2009-09-26 12:37:42 -04:00
|
|
|
@app = app
|
2011-05-03 06:32:14 -04:00
|
|
|
@file_handler = FileHandler.new(path, cache_control)
|
2009-09-26 12:37:42 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def call(env)
|
2012-12-07 01:02:43 -05:00
|
|
|
case env['REQUEST_METHOD']
|
|
|
|
when 'GET', 'HEAD'
|
|
|
|
path = env['PATH_INFO'].chomp('/')
|
|
|
|
if match = @file_handler.match?(path)
|
|
|
|
env["PATH_INFO"] = match
|
|
|
|
return @file_handler.call(env)
|
2009-09-26 12:37:42 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2012-12-07 01:02:43 -05:00
|
|
|
@app.call(env)
|
2009-09-26 12:37:42 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|