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

Dav*_*zar 8 ruby response activeresource http-headers

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

例如:product = Product.find(123)

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

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

我是否需要通过monkeypatched调用或其他方式破解Net :: HTTP或ActiveResource本身?

Kel*_*vin 5

这是一种没有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
Run Code Online (Sandbox Code Playgroud)

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

更新:这是一个修改后的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
Run Code Online (Sandbox Code Playgroud)