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

この種のことを以前に扱った人はいますか?DRYに保つようにしています。もちろん、与えられた例がパラメーターを保存するのに最適かどうかはわかりません。

4

2 に答える 2

10

これを行うにはいくつかの方法があります (これらは順不同で、すべて適切です)。

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
      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ステートメントを使用してルートをDRYする必要があるかどうかはわかりません。ルートがそれぞれ異なることをする場合は、それらを別々に書き出すだけです。より明確になり、シナトラがルートの一致で行う作業を複製しているためです。

于 2013-03-29T08:26:22.863 に答える
3

beforeフィルターの使用について:

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