gpt4 book ai didi

ruby - Active Resource 响应,如何获取它们

转载 作者:数据小太阳 更新时间:2023-10-29 06:54:02 25 4
gpt4 key购买 nike

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

例如:product = Product.find(123)

响应 header 应该包含自定义属性,例如“HTTP_PRODUCT_COUNT=20”,我想检查响应。

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

我是否需要通过 monkeypatched 调用或其他方式破解 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

关于ruby - Active Resource 响应,如何获取它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5972429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com