2012-02-20 52 views
1

出於某種原因,在西納特拉「後,」我似乎無法訪問當前狀態代碼西納特拉response.status過濾器「之後的」過濾器

require 'rubygems' 
require 'sinatra' 

after do 
    puts "After hook with code: #{response.status}" 
end 

get '/hi' do 
    halt(401, "wtf?") 
end 

當運行卷曲127.0.0.1:4567/嗨,它的結果是:

After hook for code: 200 

回答

3

它基本上是如何在Sinatra中實現方法的函數。我們需要注意的方法是call!,invokedispatch!,所有方法在Sinatra::Base(截至v1.3.2)。

call!是頂級水平的方法,並在那裏,它調用下面的代碼行:現在

invoke { dispatch! } 

invoke看起來是這樣的:

def invoke 
    res = catch(:halt) { yield } 
    res = [res] if Fixnum === res or String === res 
    if Array === res and Fixnum === res.first 
    status(res.shift) 
    body(res.pop) 
    headers(*res) 
    elsif res.respond_to? :each 
    body res 
    end 
end 

它實際上是設置響應代碼在throw:halt的基礎上。而dispatch!樣子:

def dispatch! 
    static! if settings.static? && (request.get? || request.head?) 
    filter! :before 
    route! 
rescue ::Exception => boom 
    handle_exception!(boom) 
ensure 
    filter! :after unless env['sinatra.static_file'] 
end 

請參閱ensure塊?當:halt符號已被thrown航行到堆棧軌跡時,該運行會運行。關鍵是,這是之前狀態設置代碼運行。

+0

所以沒有辦法在後過濾器中實際獲取正確的狀態碼一旦暫停參與:(? – 2012-02-20 21:36:34

+0

否,因爲它設置在'after'過濾器之後 – namelessjon 2012-02-20 21:56:03

+0

您可以將它保存在會話中var和access它從後過濾器 – three 2012-02-21 09:12:06