| Class | Rack::URLMap |
| In: |
lib/rack/urlmap.rb
|
| Parent: | Object |
Rack::URLMap takes a hash mapping urls or paths to apps, and dispatches accordingly. Support for HTTP/1.1 host names exists if the URLs start with http:// or https://.
URLMap modifies the SCRIPT_NAME and PATH_INFO such that the part relevant for dispatch is in the SCRIPT_NAME, and the rest in the PATH_INFO. This should be taken care of when you need to reconstruct the URL in order to create links.
URLMap dispatches in such a way that the longest paths are tried first, since they are most specific.
# File lib/rack/urlmap.rb, line 15
15: def initialize(map)
16: @mapping = map.map { |location, app|
17: if location =~ %r{\Ahttps?://(.*?)(/.*)}
18: host, location = $1, $2
19: else
20: host = nil
21: end
22:
23: location = "" if location == "/"
24:
25: [host, location, app]
26: }.sort_by { |(h, l, a)| -l.size } # Longest path first
27: end
# File lib/rack/urlmap.rb, line 29
29: def call(env)
30: path = env["PATH_INFO"].to_s.squeeze("/")
31: hHost, sName, sPort = env.values_at('HTTP_HOST','SERVER_NAME','SERVER_PORT')
32: @mapping.each { |host, location, app|
33: if (hHost == host || sName == host \
34: || (host.nil? && (hHost == sName || hHost == sName+':'+sPort))) \
35: and location == path[0, location.size] \
36: and (path[location.size] == nil || path[location.size] == ?/)
37: env["SCRIPT_NAME"] += location.dup
38: env["PATH_INFO"] = path[location.size..-1]
39: env["PATH_INFO"].gsub!(/\/\z/, '')
40: env["PATH_INFO"] = "/" if env["PATH_INFO"].empty?
41: return app.call(env)
42: end
43: }
44: [404, {"Content-Type" => "text/plain"}, ["Not Found: #{path}"]]
45: end