1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/actionpack/lib/action_dispatch/middleware/static.rb

73 lines
1.7 KiB
Ruby
Raw Normal View History

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('/')
2011-03-01 16:28:59 -05:00
@compiled_at = @at.blank? ? nil : /^#{Regexp.escape(at)}/
@compiled_root = /^#{Regexp.escape(root)}/
@file_server = ::Rack::File.new(@root)
2010-09-03 06:48:21 -04:00
end
2010-09-03 06:48:21 -04:00
def match?(path)
path = path.dup
if !@compiled_at || path.sub!(@compiled_at, '')
full_path = path.empty? ? @root : File.join(@root, ::Rack::Utils.unescape(path))
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
end
2010-09-03 06:48:21 -04:00
end
end
2010-09-03 06:48:21 -04:00
def call(env)
@file_server.call(env)
end
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-09-03 06:48:21 -04:00
class Static
2009-09-26 12:37:42 -04:00
FILE_METHODS = %w(GET HEAD).freeze
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
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
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