2012-11-12 112 views
3

如何檢測到活動資源find()調用返回的HTTP 206而不是典型的HTTP 200?Rails ActiveResource檢測HTTP 206響應代碼

我知道ActiveResource會爲HTTP 3xx-5xx響應代碼拋出各種異常,但是如何找出您收到的200級響應代碼呢?

+0

https://github.com/Fivell/activeresource-response試試這個寶石 – Fivell

回答

4

請參閱Active Resource responses, how to get them瞭解如何獲取線程的最後響應。然後,您可以根據需要測試響應代碼:

class MyConn < ActiveResource::Connection 
    def handle_response(resp) 
    # Store in thread (thanks fivell for the tip). 
    # Use a symbol to avoid generating multiple string instances. 
    Thread.current[:active_resource_connection_last_response] = resp 
    super 
    end 
    # this is only a convenience method. You can access this directly from the current thread. 
    def last_resp 
    Thread.current[:active_resource_connection_last_response] 
    end 
end 

class MyResource < ActiveResource::Base 
    class << self 
    attr_writer :connection 
    end 
end 

myconn = MyConn.new MyResource.connection.site 
MyResource.connection = myconn # replace with our enhanced version 
object = MyResource.find(id) 
response_code = MyResource.last_resp.code 
+0

現在嘗試了這一點。我很失望,這是得到一個簡單的響應代碼所需要的。 :( – Oleksi

+0

似乎連接=不存在ActiveResource類。任何想法? – Oleksi

+0

所以我增加了'self.connection =(value); @connection = value; end'來解決這個問題 – Oleksi