2012-11-12 111 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