Search code examples
rubyweb-servicestwitterhttp-headerscustom-headers

Twitter api headers with ruby


Mainly to get instant rate limitations (explained here › https://dev.twitter.com/docs/rate-limiting#feature-limiting), in order to call the service the cleanest way possible : on every request, it is possible to get those infos via the X-FeatureRateLimit-Limit, X-FeatureRateLimit-Remaining and X-FeatureRateLimit-Reset sent in the response header.

It is possible to get thse information by calling another endpoint (https://dev.twitter.com/docs/api/1/get/account/rate_limit_status), but well, at some point seems to consume your quota, wich makes it kind of irrelevant.

My problem is, impossible to get how to read those specific headers… Might not be that hard, but, if any help by anyone, thanks.


Solution

  • you can use twitter API wrapper that handles http header itself:

    def initialize(message, http_headers)
      @http_headers = Hash[http_headers]
      super message
    end
    
    def ratelimit_reset
      Time.at(@http_headers.values_at('x-ratelimit-reset', 'X-RateLimit-Reset').detect{|value| value}.to_i)
    end
    
    def ratelimit_limit
      @http_headers.values_at('x-ratelimit-limit', 'X-RateLimit-Limit').detect{|value| value}.to_i
    end
    
    def ratelimit_remaining
      @http_headers.values_at('x-ratelimit-remaining', 'X-RateLimit-Remaining').detect{|value| value}.to_i
    end