我有一个活动资源,可以查询数据。它返回记录、计数,无论我要求什么。
例如:product = Product.find(123)
响应标头应该包含一个自定义属性,例如“HTTP_PRODUCT_COUNT=20”,我想检查响应。
IRB 执行此操作的最有效方法是什么?我没有 Rails 或其他可能提供底层响应的框架。
我是否需要使用猴子补丁调用或其他方法来破解 Net::HTTP 或 ActiveResource 本身?
这是一种无需猴子补丁即可完成此操作的方法。
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 将使用新的连接对象重新分配连接字段。要查看何时发生这种情况,请搜索 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)