2016-07-30 75 views
0

我想自定义记录HTTP请求中的HTTP请求。这个想法是定义一个记录请求的函数。红宝石:录制一个自定义的方法

recorded :get, :post, :patch, :delete do 
    Net::HTTP.get(URI('http://www.google.com')) #will log 
end 

Net::HTTP.get(URI('http://news.ycombinator.com')) # will not log 

的问题是,我需要alias_methodNet::HTTP类的内部,并限定一个方法中的一类是不允许的。

下面是该方法的定义。

require 'net/http' 

def recorded(*methods, &block) 
    # module Net 
    # class HTTP 
    #  alias_method(:orig_request, :request) unless method_defined?(:orig_request) 
    #  alias_method(:orig_connect, :connect) unless method_defined?(:orig_connect) 
    # 
    #  def request(req, body = nil, &block) 
    #  if started? 
    #   puts :started 
    #  end 
    # 
    #  @response = orig_request(req, body, &block) 
    #  puts @response.code 
    #  # LOGGING HERE THE REQUEST 
    # 
    #  @response 
    #  end 
    # 
    #  def connect 
    #  orig_connect 
    #  end 
    # end 
    # end 

    yield block 
end 

回答

0

,您会立即体验到很多其他的问题,使用这种方法,你有这方面的问题克服,但回答说这个问题:alias_method只是一个类的方法

Net::HTTP.alias_method(:orig_request, :request) 

的以上将完美工作。但你的代码,然后从不“dealiases”回(恢复原始方法),因此任何后续调用Net::HTTP#request将依次调用的别名版本。

为了避免这种情况,可以在类Net::HTTP上设置一个实例变量,或类似的,以保持状态和路由为别名方法或原始方法。

旁注:自从Ruby2我们有Module#prepend为此目的,使用这样的别名方法看起来像遗产。