【问题标题】:Ruby: Recording HTTP requests inside a custom methodRuby:在自定义方法中记录 HTTP 请求
【发布时间】:2016-12-05 05:44:24
【问题描述】:

我正在尝试自定义记录 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

问题是我需要在Net::HTTP 类中使用alias_method,并且不允许在方法中定义类。

这是方法定义。

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

【问题讨论】:

    标签: ruby-on-rails ruby http request net-http


    【解决方案1】:

    当您克服了这个特殊问题时,您将立即遇到许多其他问题,但回答上述问题:alias_method 只是一个类方法

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

    以上将完美地工作。但是您的代码永远不会“dealiases”它返回(恢复原始方法),因此对Net::HTTP#request 的任何后续调用将依次调用别名版本。

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

    旁注:自 Ruby2 以来,我们有 Module#prepend 用于此目的,使用这种别名方法看起来像旧的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      • 2023-03-21
      相关资源
      最近更新 更多