我有一条共同的基本道路;说:get /base
我需要执行基本身份验证并为该路径下的所有子调用工作。说:get /base/foo
和get /base/bar
。
查看http://www.sinatrarb.com/intro.html#Helpers建议我应该可以使用助手来做到这一点。我一直在寻找pass
帮助程序,并在触发文档中的新路由下使用call
。但是,我读到的另一个建议是使用正则表达式IE %r{/base/?:(path)?}
或类似的东西使用动态路由。那么呢:
def '/base'
# do some funky basic auth stuff here
# to work with all request to this common
# base path?
pass
end
def %r{/base/?(path)?} do |path|
case path
when 'foo'
# do something.
when 'bar'
# do something else.
end
# some kind of redirection or template rendering here:
erb :template
end
以前有没有人处理过这种事情?我正在尝试使其保持干燥。当然,我不确定给出的示例在保留参数方面是否是最好的。
最佳答案
有几种方法可以做到这一点(这些顺序不对,它们都很好):
具有一个before块和一个辅助对象的命名空间
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
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
authenticate!
# funky auth stuff
# but no need for `pass`
end
end
before '/base/*' do
authenticate!
end
映射的应用
class MyBase < Sinatra::Base
helpers do
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在匹配路由中所做的工作。
关于ruby - 在共同的基本路线之上建立路线?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15695861/