如何在Sinatra中映射到控制器的路由? [英] How to map routes to controllers in Sinatra?
问题描述
我想使用Sinatra创建一个简单的实验性MVC框架.
I'd like to create a simple experimental MVC framework using Sinatra.
我想通过名称"pages"
定义资源,例如应解析为:
I'd like to define resources by name "pages"
for example should resolve to:
/pages (index)
/pages/new
/pages/:id/show (show)
与映射到app/controllers/PagesController.rb
的WELL相对应,其中get('/')
负责索引,post('/pages/create')
负责创建,等等.
as WELL as map to app/controllers/PagesController.rb
with corresponding get('/')
to be responsible for the index, post('/pages/create')
be responsible for creation, etc.
即使阅读了官方文档,问题仍然困扰着我.我想我需要为此使用非经典的Sinatra模型,但是有人可以指出正确的方向吗?
Trouble is even after reading the official documentation I'm terribly confused. I imagine I need to use non-classic Sinatra model for this, but could anyone point me in the right direction?
谢谢
推荐答案
如果您想要我想要的东西,我会一直这样做.最初,对于该方案,我使用travis-api源作为参考,但是本质上您想要做的是在"controller"类中扩展Sinatra :: Base,然后将您的各个Sinatra"controllers"安装在机架中,就像这样:
If you want what I think you're wanting, I do this all the time. Initially for this scheme I used the travis-api source as a reference, but essentially what you want to do is extend Sinatra::Base in a "controller" class and then mount up your individual Sinatra "controllers" in rack, something like this:
module Endpoint
def self.included(base)
base.class_eval do
set(:prefix) { "/" << name[/[^:]+$/].downcase }
end
end
end
class Users < Sinatra::Base
include Endpoint
get '/' do
#logic here
end
get '/:id' do
#logic here
end
post '/' do
#logic here
end
patch '/:id' do
#logic here
end
end
class Posts < Sinatra::Base
include Endpoint
post '/' do
#logic here
end
end
然后是这样的:
class App
require "lib/endpoints/users"
require "lib/endpoints/posts"
attr_reader :app
def initialize
@app = Rack::Builder.app do
[Users, Posts].each do |e|
map(e.prefix) { run(e.new) }
end
end
end
def call(env)
app.call(env)
end
end
您可以根据需要进行调整,但是想法是相同的,您将应用程序分为可组合的Sinatra应用程序,每个应用程序都有一个前缀,并使用Rack挂载了这些前缀.这个特定的示例将为您提供以下路线:
You can adjust this to whatever you need, but the idea is the same, you separate your app into composable Sinatra applications that each have a prefix that they are mounted under using Rack. This particular example will give you routes for:
获取"/用户"
获取'/users/:id'
get '/users/:id'
发布'/users'
修补'/users/:id'
patch '/users/:id'
获取"/帖子"
这篇关于如何在Sinatra中映射到控制器的路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!