Class: X::RateLimit

Inherits:
Object
  • Object
show all
Defined in:
lib/x/rate_limit.rb

Overview

Represents rate limit information from an API response

Constant Summary collapse

RATE_LIMIT_TYPE =

Rate limit type identifier

"rate-limit".freeze
APP_LIMIT_TYPE =

App limit type identifier

"app-limit-24hour".freeze
USER_LIMIT_TYPE =

User limit type identifier

"user-limit-24hour".freeze
TYPES =

All supported rate limit types

[RATE_LIMIT_TYPE, APP_LIMIT_TYPE, USER_LIMIT_TYPE].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type:, response:) ⇒ RateLimit

Initialize a new RateLimit

Examples:

Create a rate limit instance

rate_limit = X::RateLimit.new(type: "rate-limit", response: response)

Parameters:

  • type (String)

    the type of rate limit

  • response (Net::HTTPResponse)

    the HTTP response containing rate limit headers



36
37
38
39
# File 'lib/x/rate_limit.rb', line 36

def initialize(type:, response:)
  @type = type
  @response = response
end

Instance Attribute Details

#responseNet::HTTPResponse

The HTTP response containing rate limit headers

Examples:

Get or set the response

rate_limit.response = http_response

Returns:

  • (Net::HTTPResponse)

    the HTTP response containing rate limit headers



26
27
28
# File 'lib/x/rate_limit.rb', line 26

def response
  @response
end

#typeString

The type of rate limit

Examples:

Get or set the rate limit type

rate_limit.type = "rate-limit"

Returns:

  • (String)

    the type of rate limit



19
20
21
# File 'lib/x/rate_limit.rb', line 19

def type
  @type
end

Instance Method Details

#limitInteger

Get the rate limit maximum

Examples:

Get the rate limit

rate_limit.limit

Returns:

  • (Integer)

    the maximum number of requests allowed



47
48
49
# File 'lib/x/rate_limit.rb', line 47

def limit
  Integer(response.fetch("x-#{type}-limit"))
end

#remainingInteger

Get the remaining requests

Examples:

Get the remaining requests

rate_limit.remaining

Returns:

  • (Integer)

    the number of requests remaining



57
58
59
# File 'lib/x/rate_limit.rb', line 57

def remaining
  Integer(response.fetch("x-#{type}-remaining"))
end

#reset_atTime

Get the time when the rate limit resets

Examples:

Get the reset time

rate_limit.reset_at

Returns:

  • (Time)

    the time when the rate limit resets



67
68
69
# File 'lib/x/rate_limit.rb', line 67

def reset_at
  Time.at(Integer(response.fetch("x-#{type}-reset")))
end

#reset_inInteger Also known as: retry_after

Get the seconds until the rate limit resets

Examples:

Get the reset time in seconds

rate_limit.reset_in

Returns:

  • (Integer)

    the seconds until the rate limit resets



77
78
79
# File 'lib/x/rate_limit.rb', line 77

def reset_in
  [(reset_at - Time.now).ceil, 0].max
end