我有一个用于查询数据的活动资源。它返回记录,计数,无论我要求什么。
例如:产品 = Product.find(123)
响应标头应该包含一个自定义属性,例如“HTTP_PRODUCT_COUNT=20”,我想检查响应。
从 IRB 执行此操作的最有效方法是什么?我没有可能提供底层响应的 Rails 或其他框架。
我是否需要通过猴子补丁调用或其他方式破解 Net::HTTP 或 ActiveResource 本身?
我有一个用于查询数据的活动资源。它返回记录,计数,无论我要求什么。
例如:产品 = Product.find(123)
响应标头应该包含一个自定义属性,例如“HTTP_PRODUCT_COUNT=20”,我想检查响应。
从 IRB 执行此操作的最有效方法是什么?我没有可能提供底层响应的 Rails 或其他框架。
我是否需要通过猴子补丁调用或其他方式破解 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
如果您更改某些类字段,例如站点,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
你也可以试试这个 gem https://github.com/Fivell/activeresource-response