Class: ApiKeyManager::RateLimited
- Inherits:
-
Object
- Object
- ApiKeyManager::RateLimited
- Defined in:
- lib/api_key_manager/rate_limited.rb
Overview
api_key_manager/lib/api_key_manager/rate_limited.rb
Instance Method Summary collapse
- #api_key ⇒ Object (also: #key)
-
#initialize(api_keys:, delay: false, rate_count: 5, rate_period: 60) ⇒ RateLimited
constructor
A new instance of RateLimited.
- #reset_counter ⇒ Object
- #reset_timer ⇒ Object
Constructor Details
#initialize(api_keys:, delay: false, rate_count: 5, rate_period: 60) ⇒ RateLimited
Returns a new instance of RateLimited.
5 6 7 8 9 10 11 12 13 14 |
# File 'lib/api_key_manager/rate_limited.rb', line 5 def initialize(api_keys:, delay: false, rate_count: 5, rate_period: 60) @api_keys = api_keys.is_a?(String) ? api_keys.split(',') : api_keys @delay = delay @rate_count = rate_count.is_a?(String) ? rate_count.to_i : rate_count @rate_period = rate_period.is_a?(String) ? rate_period.to_i : rate_period @start_timer = Time.now.to_i @end_timer = @start_timer - 1 # prevent delay @counter = @rate_count @current_index = 0 end |
Instance Method Details
#api_key ⇒ Object Also known as: key
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/api_key_manager/rate_limited.rb', line 36 def api_key now = Time.now.to_i if now <= @end_timer && @counter < 1 @current_index = (@current_index + 1) % @api_keys.length reset_timer reset_counter elsif now > @end_timer # Continue using same api key reset_timer reset_counter end @counter -= 1 @api_keys[@current_index] end |
#reset_counter ⇒ Object
17 18 19 |
# File 'lib/api_key_manager/rate_limited.rb', line 17 def reset_counter @counter = @rate_count end |
#reset_timer ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/api_key_manager/rate_limited.rb', line 22 def reset_timer now = Time.now.to_i if @delay && now < @end_timer delta = @end_timer - now sleep(delta) # NOTE: Will block IO process now = Time.now.to_i end @start_timer = now @end_timer = @start_timer + @rate_period end |