有几种方法可以做到这一点(这些没有任何顺序,它们都很好):
带有前块和助手的命名空间
http://rubydoc.info/gems/sinatra-contrib/1.3.2/Sinatra/Namespace
require 'sinatra/namespace'
class App < Sinatra::Base
register Sinatra::Namespace
namespace "/base" do
helpers do # this helper is now namespaced too
def authenticate!
# funky auth stuff
# but no need for `pass`
end
end
before do
authenticate!
end
get "/anything" do
end
get "/you" do
end
get "/like/here" do
end
end
带条件的命名空间
require 'sinatra/namespace'
class App < Sinatra::Base
register Sinatra::Namespace
set(:auth) do |*roles| # <- notice the splat here
condition do
unless logged_in? && roles.any? {|role| current_user.in_role? role }
redirect "/login/", 303
end
end
end
namespace "/base", :auth => [:user] do
# routes…
end
namespace "/admin", :auth => [:admin] do
# routes…
end
助手和前置过滤器
helpers do
def authenticate!
# funky auth stuff
# but no need for `pass`
end
end
before '/base/*' do
authenticate!
end
映射的应用程序
class MyBase < Sinatra::Base
helpers do
def authenticate!
# funky auth stuff
# but no need for `pass`
end
end
before do
authenticate!
end
get "/" do
end
get "/another" do
end
end
# in rackup file
map "/" do
run App1
end
map "/base" do
# every route in MyBase will now be accessed by prepending "/base"
# e.g. "/base/" and "/base/another"
run MyBase
end
#…
我不确定是否需要使用 case 语句来干燥路线。如果每条路线都做不同的事情,那么我只需将它们单独写出来,因为它更清晰,并且您正在复制 Sinatra 在匹配路线中所做的工作。