我没有发现如何从其他模块混合路由,如下所示:
module otherRoutes
get "/route1" do
end
end
class Server < Sinatra::Base
include otherRoutes
get "/" do
#do something
end
end
Run Code Online (Sandbox Code Playgroud)
那可能吗?
ale*_*nde 28
你没有包括 Sinatra.您将扩展与注册一起使用.
即在单独的文件中构建您的模块:
require 'sinatra/base'
module Sinatra
module OtherRoutes
def self.registered(app)
app.get "/route1" do
...
end
end
end
register OtherRoutes # for non modular apps, just include this file and it will register
end
Run Code Online (Sandbox Code Playgroud)
然后注册:
class Server < Sinatra::Base
register Sinatra::OtherRoutes
...
end
Run Code Online (Sandbox Code Playgroud)
从文档中可以清楚地看出,这是非基本Sinatra应用程序的方法.希望它能帮助别人.
你可以这样做:
module OtherRoutes
def self.included( app )
app.get "/route1" do
...
end
end
end
class Server < Sinatra::Base
include OtherRoutes
...
end
Run Code Online (Sandbox Code Playgroud)
与Ramaze不同,Sinatra的路由不是方法,因此不能直接使用Ruby的方法查找链接.请注意,使用此功能,您无法在以后对其进行猴子修补,并将更改反映在Server中; 这只是定义路线的一次性便利.
小智 6
那么你也可以使用map方法将路线映射到你的sinatra应用程序
map "/" do
run Rack::Directory.new("./public")
end
map '/posts' do
run PostsApp.new
end
map '/comments' do
run CommentsApp.new
end
map '/users' do
run UserssApp.new
end
Run Code Online (Sandbox Code Playgroud)
我更喜欢使用 sinatra-contrib gem 来扩展 sinatra 以获得更清晰的语法和共享命名空间
# Gemfile
gem 'sinatra', '~> 1.4.7'
gem 'sinatra-contrib', '~> 1.4.6', require: 'sinatra/extension'
# other_routes.rb
module Foo
module OtherRoutes
extend Sinatra::Extension
get '/some-other-route' do
'some other route'
end
end
end
# app.rb
module Foo
class BaseRoutes < Sinatra::Base
get '/' do
'base route'
end
register OtherRoutes
end
end
Run Code Online (Sandbox Code Playgroud)
sinata-contrib与 sinatra 项目一起维护
| 归档时间: |
|
| 查看次数: |
8004 次 |
| 最近记录: |