主动资源响应,如何获取它们

我有一个活动资源,我查询数据。 它返回记录,计数,无论我要求什么。

例如:product = Product.find(123)

响应头应该包含一个自定义属性,比如“HTTP_PRODUCT_COUNT = 20”,我想检查响应。

IRB最有效的方法是什么? 我没有奢侈的Rails或其他可能提供底层响应的框架。

我是否需要使用monkeypatched调用或其他东西攻击Net :: HTTP或ActiveResource本身?

这是一种没有monkeypatching的方法。

class MyConn < ActiveResource::Connection attr_reader :last_resp def handle_response(resp) @last_resp=resp super end end class Item < ActiveResource::Base class << self attr_writer :connection end self.site = 'http://yoursite' end # Set up our own connection myconn = MyConn.new Item.connection.site Item.connection = myconn # replace with our enhanced version item = Item.find(123) # you can also access myconn via Item.connection, since we've assigned it myconn.last_resp.code # response code myconn.last_resp.to_hash # header 

如果更改某些类字段(如site),ARes将使用新的Connection对象重新分配连接字段。 要查看何时发生这种情况,请在active_resource / base.rb中搜索@connection设置为nil的位置。 在这些情况下,您将不得不再次分配连接。

更新:这是一个应该是线程安全的修改后的MyConn。 (用fivell的建议重新编辑)

 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 
 module ActiveResource class Connection alias_method :origin_handle_response, :handle_response def handle_response(response) Thread.current[:active_resource_connection_headers] = response origin_handle_response(response) end def response Thread.current[:active_resource_connection_headers] end end end 

你也可以尝试这个gemhttps://github.com/Fivell/activeresource-response