Sub routing in Sinatra

一世执手 提交于 2019-12-11 23:45:41

问题


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 be more specific, here's an example:

  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 and

helpers/article_api.rb

They each extend SinatraBase like so:

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

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

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.

My config.ru looks like this:

$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

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?

Thanks


回答1:


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

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



来源:https://stackoverflow.com/questions/15077000/sub-routing-in-sinatra

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