6

我有一个共同的基本路径;说:get /base我需要执行基本身份验证并为该路径下的所有子调用工作。说:get /base/fooget /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

有没有人处理过这种事情?我试图让它保持干燥。当然,我不确定给定的示例是否是保存参数的最佳示例。

4

2 回答 2

10

有几种方法可以做到这一点(这些没有任何顺序,它们都很好):

带有前块和助手的命名空间

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 在匹配路线中所做的工作。

于 2013-03-29T08:26:22.863 回答
3

如何使用before过滤器:

before '/base/?*' do
    @foo = 'bar'
end
于 2013-03-29T01:27:22.060 回答