URL Map an entire namespace using rack mount?

梦想的初衷 提交于 2020-01-06 03:57:27

问题


I have two modular Sinatra rack based applications: core.rb & project.rb:

# core.rb
class Core < Sinatra::Base
  get "/" do
    "Hello, world!"
  end
end

# project.rb
class Project < Sinatra::Base
  get "/" do
    "A snazzy little Sinatra project I wish to showcase."
  end
  get "/foo" do
    "If you see this, congratulations."
  end
end

My goal is simply to map the entire /projects namespace to the Project class, wheras everything else is handled by the Core class. I found that you can do this to a limited extent in 2 ways:

# config.ru
require "./core.rb"
require "./projects.rb"

map "/projects" do
  # Method #1: Using Sinatra's built-in Middleware
  use Project
  # Method #2: Using Rack::Cascade
  run Rack::Cascade.new( [Project, Core] )
end
run Core

Both of the methods I tried above have the same effect. The routes / and /projects show up correctly, however when going to /projects/foo it throws an error which states it can't find the /foo route in my main core.rb file - which is NOT what I want. In other words it's looking for my /foo route in the wrong file :(

So, is it possible to map across the entire /projects namespace using rack-mount? And no, adding "/projects/" to all my routes in project.rb is not an option here I'm afraid.


回答1:


Your config.ru file seems to work okay when I test it, but it looks a little confused. Here’s a simpler example that achieves the same thing:

map "/projects" do
  run Project # note run, not use
end
run Core

Now any request where the path starts with /projects will be routed to the Project app, and all other will go to Core, which is associated with the root path automatically.



来源:https://stackoverflow.com/questions/21453337/url-map-an-entire-namespace-using-rack-mount

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!