我正在尝试在Sinatra应用程序中使用子类化样式.所以,我有一个像这样的主要应用程序.
class MyApp < Sinatra::Base
get '/'
end
...
end
class AnotherRoute < MyApp
get '/another'
end
post '/another'
end
end
Run Code Online (Sandbox Code Playgroud)
run Rack::URLMap.new \
"/" => MyApp.new,
"/another" => AnotherRoute.new
Run Code Online (Sandbox Code Playgroud)
在config.ru我明白它只是为了"GET"如何关于其他资源(例如"PUT","POST")?我不确定我是否错过了一些明显的东西.而且,如果我有十个路径(/ path1,/ path2,...),我是否必须在config.ru中配置它们,即使它们在同一个类中?
Mor*_*gan 15
app.rb
class MyApp < Sinatra::Base
get '/'
end
end
Run Code Online (Sandbox Code Playgroud)
app2.rb如果你想要两个单独的文件.请注意,这继承自Sinatra :: Base而不是MyApp.
class AnotherRoute < Sinatra::Base
get '/'
end
post '/'
end
end
Run Code Online (Sandbox Code Playgroud)
config.ru
require 'bundler/setup'
Bundler.require(:default)
require File.dirname(__FILE__) + "/lib/app.rb"
require File.dirname(__FILE__) + "/lib/app2.rb"
map "/" do
run MyApp
end
map "/another" do
run AnotherRoute
end
Run Code Online (Sandbox Code Playgroud)
你可以把它写成
class MyApp < Sinatra::Base
get '/'
end
get '/another'
end
post '/another'
end
end
Run Code Online (Sandbox Code Playgroud)
在config.ru中
require './my_app'
run MyApp
Run Code Online (Sandbox Code Playgroud)
跑:
rackup -p 1234
Run Code Online (Sandbox Code Playgroud)
请参阅http://www.sinatrarb.com/intro#Serving%20a%20Modular%20Application上的文档
您指定URLMap
应安装应用程序的基本 url。确定在应用程序本身内使用哪条路线时,不会使用地图中指定的路径。换句话说,应用程序的行为就好像它的根目录位于URLMap
.
例如,您的代码将响应以下路径:
/
: 将被路由到/
以下路径MyApp
/another
: 将前往/
中的路线AnotherRoute
。由于AnotherRoute
扩展,这将与中MyApp
相同(但在不同的实例中)。/
MyApp
URLMap
看到/another
并使用它来映射到AnotherRoute
,从路径中剥离请求的这一部分。AnotherRoute
然后才看到/
。
/another/another
/another
: 将被路由到中的两条路由AnotherRoute
。another
同样, URLMap 使用第一个将请求路由到AnotherRoute
. AnotherRoute
然后只将第二个视为another
路径。
请注意,此路径将响应GET
和POST
请求,每个请求都由适当的块处理。
目前尚不清楚你想要做什么,但我认为你可以通过运行 的实例来实现你想要的AnotherRoute
,其中的 aconfig.ru
只是:
run AnotherRoute.new
Run Code Online (Sandbox Code Playgroud)
由于AnotherRoute
extends MyApp
,/
将为其定义路由。
如果您正在寻找一种向现有 Sinatra 应用程序添加路由的方法,您可以使用添加路由的方法创建一个模块included
,而不是使用继承。
归档时间: |
|
查看次数: |
13562 次 |
最近记录: |