Display rack urls

I am trying to write two kinds of Rack routes. The stand allows us to write such routes as follows:

app = Rack::URLMap.new('/test' => SimpleAdapter.new, '/files' => Rack::File.new('.')) 

In my case, I would like to handle these routes:

  • "/" or "index"
  • "/ *" to match any other routes

So, I tried this:

 app = Rack::URLMap.new('/index' => SimpleAdapter.new, '/' => Rack::File.new('./public')) 

This works well, but ... I don't know how to add the path '/' (as an alternative to the path '/ index'). In my tests, the path '/ *' is not interpreted as a wildcard. Do you know how I could do this?

thanks

+4
source share
1 answer

You are correct that Rack::URLMap does not treat '*' in the path as a wildcard. The actual translation from the regex path is as follows:

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

That is, it treats any characters in the path as literals, but also matches the path with any suffix. I believe that the only way to achieve what you are trying is to use middleware instead of the endpoint. In your config.ru you might have something like this:

 use SimpleAdapter run Rack::File 

And your lib/simple_adapter.rb might look something like this:

 class SimpleAdapter SLASH_OR_INDEX = %r{/(?:index)?} def initialize(app) @app = app end def call(env) request = Rack::Request.new(env) if request.path =~ SLASH_OR_INDEX # return some Rack response triple... else # pass the request on down the stack: @app.call(env) end end end 
+3
source

Source: https://habr.com/ru/post/1305378/


All Articles