主动资源响应,如何获取它们 [英] Active Resource responses, how to get them

查看:253
本文介绍了主动资源响应,如何获取它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an Active Resource that I query for data. It returns records, counts, whatever I ask for.

例如:product = Product.find(123)

eg: product = Product.find(123)

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

The response headers supposedly contain a custom attribute, say "HTTP_PRODUCT_COUNT=20" and I would like to examine the response.

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

What would be the most efficient way of doing this from IRB? I don't have the luxury of Rails or other frameworks that might provide the underlying response.

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

Do I need to hack Net::HTTP or ActiveResource itself with a monkeypatched call or something?

推荐答案

这是一种没有monkeypatching的方法。

Here's one way to do it without 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的位置。在这些情况下,您将不得不再次分配连接。

If you change certain class fields like site, ARes will re-assign the connection field with a new Connection object. To see when this happens, search active_resource/base.rb for where @connection is set to nil. In these cases you'll have to assign the connection again.

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

UPDATE: Here's a modified MyConn that should be thread-safe. (re-edited with fivell's suggestion)

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

这篇关于主动资源响应,如何获取它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆