Ruby - 速率限制的访问响应 Headers(帮助 Scout)

Ruby - Access Response Headers for Rate Limiting (Help Scout)

我正在使用 helpscout ruby gem 并尝试检查请求限制何时低于特定数量(即剩余 2 个请求)并让剩余的循环休眠允许重置速率限制的时间间隔。

有没有办法在发出请求时从 API 访问响应 headers? https://developer.helpscout.com/help-desk-api/#basic-rate-limiting

X-RateLimit-Interval-*  Length of the rate limiting interval in seconds

X-RateLimit-Limit-* Maximum number of requests per interval

X-RateLimit-Remaining-* Number of requests remaining in the current rate limit interval

Intercom (https://developers.intercom.com/reference#rate-limiting) 允许您检查 rate_limit_details 和 returns headers,但我找不到任何帮助 Scout或了解如何访问它们。

intercom.rate_limit_details
#=> {:limit=>180, :remaining=>179, :reset_at=>2014-10-07 14:58:00 +0100}

问题是 helpscout gem 没有捕获该信息。如果你看源码

https://github.com/hramos/helpscout/blob/db8da936853c8df694186ab11100d4482f74d302/lib/helpscout/models.rb#L44

  # Error Envelope
  class ErrorEnvelope
    attr_reader :status, :message

    # Creates a new ErrorEnvelope object from a Hash of attributes
    def initialize(object)
      @status = object["status"]
      @message = object["message"]
    end
  end

当发生错误时,他们只捕获 statusmessage。如果您想捕获额外的 header 值

,您可以增强下面的 class
  # Error Envelope
  class ErrorEnvelope
    attr_reader :status, :message, :limit

    # Creates a new ErrorEnvelope object from a Hash of attributes
    def initialize(object)
      @status = object["status"]
      @message = object["message"]
      @limit = object["header"]["X-RateLimit-...."]
    end
  end

但这只会在您遇到错误时告诉您限制。您可以进一步增强库以在每次调用时捕获这些限制。您将需要修改 client.rb

https://github.com/hramos/helpscout/blob/2449bc2604667edfca5ed934c8e61cd129b17af5/lib/helpscout/client.rb

module HelpScout
  class Client
    include HTTParty
    @@last_headers

    def self.get(*more)
        response = HTTParty.get(*more)
        @@last_headers = response.headers
        return response
    end

    def self.last_headers
        @@last_headers
    end

    ....
    ....
 end

这样做 HelpScout.last_headers 将为您提供来自上次响应的 headers,然后您可以从相同的

中捕获您需要的任何字段