Sinatra中的子路由

问题描述:

有没有一种方法可以将不同的控制器映射到彼此相关的url,特别是当一个是另一个的子资源时?

Is there a way by which one can map different controllers to urls that are related to each other, specifically when one is a sub resource of the other?

To更具体地讲,这是一个示例:

To be more specific, here's an example:


  1. 我有2种资源:工作 c >和文章工作包含多个文章。尽管它们之间存在关系,但我想在单独的文件中处理与每个代码相关的实际代码。因此,我有:

  1. I have 2 types of resources: jobs and articles. A job contains multiple articles. Despite their relationship, I want to handle the actual code related to each in separate files. As such I have:

helpers / job_api.rb

helpers / article_api.rb

它们每个都像SinatraBase一样扩展因此:

They each extend SinatraBase like so:

class ArticleAPI < Sinatra::Base
  register Sinatra::Async

  get '/list' do
  #...
  end
end

我现在想要的是将所有属于作业的URL请求仅映射到 JobAPI 和属于文章的文章(但仍始终与单个作业关联到 ArticleAPI

What I want now is to map all url requests that belong to jobs only to the JobAPI and the ones that belong to articles (but still are associated with a single job at all times to the ArticleAPI.

我的 config.ru 看起来像这样:

$ LOAD_PATH<<'。 '
需要'server'

$LOAD_PATH << '.' require 'server'

map "/" do
  run Sinatra::Application
end

map "/job" do
  run JobAPI
end

map "/job/:job_id/article" do
  run ArticleAPI
end

但这在我尝试转到url时不起作用 /职位/ 12 /文章/列表

But that doesn't work when I try to go to the url /job/12/article/list.

任何人都知道是否有办法吗?

Anyone know if there's a way to do this?

谢谢

config中执行的代码.ru 文件用于机架,它具有与 Sinatra 可以。意味着这段代码:

The code executing in your config.ru file is for Rack which does not have the same routing syntax as Sinatra does. Meaning that this code:

map "/job/:job_id/article" do
  run ArticleAPI
end

可能在 config.ru $内部不起作用c $ c>因为Rack不能像Sinatra那样处理路径中的参数。

Probably won't work inside of the config.ru because Rack doesn't handle parameters in the paths, the way Sinatra does.