简体   繁体   中英

What is “map” matching exactly in Rack?

Say I have this in Rack:

map '/great' do
  run Test.new
end

This URL works great: site.com/great/stuff but this does NOT: site.com/greatstuff . I've read that map should match anything that STARTS WITH the the arg name, but this doesn't seem to be the case, with cases like these.

Is there any detailed specification on how this works?

The confusion seems to be conceptual.

It does match paths starting with /great . That is /great , /great/ , /great/stuff and so on. What it doesn't do is match strings starting with /great . Like /greatstuff .

/greatstuff and /great are completely different paths. Think of paths as a tree structure.


There is no way to do "string path matching" with barebones map AFAIK, but you could add your own rack middleware that looks at the request path and dispatches appropriately.


If you want to double check the implementation, here are the two relevant places: 1 , 2 .

Regexp.new("^#{Regexp.quote(location).gsub('/', '/+')}(.*)", nil, 'n')

This basically creates a regex out of a path that requires a string to start with that path (multiple / ignored) in order to match. Aka:

to_regex('/foo/bar') # => /^\/+foo\/+bar(.*)/n

In case you are wondering, the n flag sets the encoding to ASCII.

If the string matches, a few more checks are performed. Namely that the remainder of the matched path is either non-existent or starts with / . The latter ensures that you won't match things like /greatstuff with /great , as stuff doesn't start with / .

next unless !rest || rest.empty? || rest[0] == ?/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM