| 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: @mapping.each { |host, location, app|
32: if (env["HTTP_HOST"] == host ||
33: env["SERVER_NAME"] == host ||
34: (host == nil && (env["HTTP_HOST"] == env["SERVER_NAME"] ||
35: env["HTTP_HOST"] ==
36: "#{env["SERVER_NAME"]}:#{env["SERVER_PORT"]}"))) &&
37: location == path[0, location.size] && (path[location.size] == nil ||
38: path[location.size] == ?/)
39: env["SCRIPT_NAME"] = location.dup
40: env["PATH_INFO"] = path[location.size..-1]
41: env["PATH_INFO"].gsub!(/\/\z/, '')
42: env["PATH_INFO"] = "/" if env["PATH_INFO"].empty?
43: return app.call(env)
44: end
45: }
46: [404, {"Content-Type" => "text/plain"}, ["Not Found: #{path}"]]
47: end