Class: ApiEntreprise::Commons::RateLimit

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(limit:, remaining:, reset_at:) ⇒ RateLimit

Returns a new instance of RateLimit.



37
38
39
40
41
# File 'lib/api_entreprise/commons/rate_limit.rb', line 37

def initialize(limit:, remaining:, reset_at:)
  @limit = limit
  @remaining = remaining
  @reset_at = reset_at
end

Instance Attribute Details

#limitObject (readonly)

Returns the value of attribute limit.



7
8
9
# File 'lib/api_entreprise/commons/rate_limit.rb', line 7

def limit
  @limit
end

#remainingObject (readonly)

Returns the value of attribute remaining.



7
8
9
# File 'lib/api_entreprise/commons/rate_limit.rb', line 7

def remaining
  @remaining
end

#reset_atObject (readonly)

Returns the value of attribute reset_at.



7
8
9
# File 'lib/api_entreprise/commons/rate_limit.rb', line 7

def reset_at
  @reset_at
end

Class Method Details

.from_headers(headers) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/api_entreprise/commons/rate_limit.rb', line 9

def self.from_headers(headers)
  return nil if headers.nil?

  normalized = headers.transform_keys { |k| k.to_s.downcase }
  limit = parse_int(normalized['ratelimit-limit'])
  remaining = parse_int(normalized['ratelimit-remaining'])
  reset_at = parse_reset(normalized['ratelimit-reset'])

  return nil if limit.nil? && remaining.nil? && reset_at.nil?

  new(limit: limit, remaining: remaining, reset_at: reset_at)
end

.parse_int(value) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/api_entreprise/commons/rate_limit.rb', line 22

def self.parse_int(value)
  return nil if value.nil? || value.to_s.strip.empty?

  Integer(value.to_s, 10)
rescue ArgumentError
  nil
end

.parse_reset(value) ⇒ Object



30
31
32
33
34
35
# File 'lib/api_entreprise/commons/rate_limit.rb', line 30

def self.parse_reset(value)
  ts = parse_int(value)
  return nil if ts.nil?

  Time.at(ts).utc
end

Instance Method Details

#retry_after(now: Time.now) ⇒ Object



43
44
45
46
47
48
# File 'lib/api_entreprise/commons/rate_limit.rb', line 43

def retry_after(now: Time.now)
  return nil if reset_at.nil?

  diff = reset_at.to_i - now.to_i
  diff.negative? ? 0 : diff
end

#to_hObject



50
51
52
# File 'lib/api_entreprise/commons/rate_limit.rb', line 50

def to_h
  { limit: limit, remaining: remaining, reset_at: reset_at }
end