| 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: unless location[0] == ?/
24: raise ArgumentError, "paths need to start with /"
25: end
26: location = location.chomp('/')
27:
28: [host, location, app]
29: }.sort_by { |(h, l, a)| -l.size } # Longest path first
30: end
# File lib/rack/urlmap.rb, line 32
32: def call(env)
33: path = env["PATH_INFO"].to_s.squeeze("/")
34: hHost, sName, sPort = env.values_at('HTTP_HOST','SERVER_NAME','SERVER_PORT')
35: @mapping.each { |host, location, app|
36: next unless (hHost == host || sName == host \
37: || (host.nil? && (hHost == sName || hHost == sName+':'+sPort)))
38: next unless location == path[0, location.size]
39: next unless path[location.size] == nil || path[location.size] == ?/
40: env["SCRIPT_NAME"] += location
41: env["PATH_INFO"] = path[location.size..-1]
42: return app.call(env)
43: }
44: [404, {"Content-Type" => "text/plain"}, ["Not Found: #{path}"]]
45: end