8

データをクエリするアクティブなリソースがあります。レコード、カウント、私が求めるものは何でも返します。

例: product = Product.find(123)

応答ヘッダーには、「HTTP_PRODUCT_COUNT = 20」などのカスタム属性が含まれていると思われ、応答を調べたいと思います。

IRB からこれを行う最も効率的な方法は何でしょうか? Rails や、基本的な応答を提供する可能性のあるその他のフレームワークを利用する余裕はありません。

モンキーパッチを適用した呼び出しなどで Net::HTTP または ActiveResource 自体をハックする必要がありますか?

4

2 に答える 2

7

モンキーパッチを使わずにそれを行う1つの方法を次に示します。

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
于 2011-07-19T17:57:26.323 に答える
4
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    

また、この宝石を試すこともできますhttps://github.com/Fivell/activeresource-response

于 2011-12-26T15:16:56.810 に答える