Class: ErpIntegration::RateLimiter

Inherits:
Object
  • Object
show all
Defined in:
lib/erp_integration/rate_limiter.rb

Defined Under Namespace

Classes: MissingMethodError, Unlimited

Constant Summary collapse

REQUIRED_METHODS =

The ‘api_key_fragment` method should return a string that is used to identify the rate limiter by the API key.

The ‘within_limit` method should yield to the block if the rate limit is not exceeded.

%i[api_key_fragment name within_limit].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rate_limiter) ⇒ RateLimiter

Returns a new instance of RateLimiter.



58
59
60
# File 'lib/erp_integration/rate_limiter.rb', line 58

def initialize(rate_limiter)
  @rate_limiter = rate_limiter
end

Class Method Details

.find_by_api_key(api_key) ⇒ Object

Finds the rate limiter by the API key. If the API key is not found, it returns an unlimited rate limiter.

Parameters:

  • api_key (String)

Returns:

  • (Object)

    The rate limiter object.



31
32
33
# File 'lib/erp_integration/rate_limiter.rb', line 31

def find_by_api_key(api_key)
  new(rate_limiters[api_key] || unlimited)
end

.unlimitedRateLimiter::Unlimited

Returns an unlimited rate limiter.

Returns:



38
39
40
# File 'lib/erp_integration/rate_limiter.rb', line 38

def unlimited
  @unlimited ||= Unlimited.new
end

.validate!(rate_limiter) ⇒ Object

Validates that the rate limiter object responds to the required methods. It requires the ‘api_key_fragment` and `within_limit` methods to be present.

Parameters:

  • rate_limiter (Object)

Raises:



18
19
20
21
22
23
24
# File 'lib/erp_integration/rate_limiter.rb', line 18

def validate!(rate_limiter)
  REQUIRED_METHODS.each do |method|
    next if rate_limiter.respond_to?(method)

    raise MissingMethodError, "'#{rate_limiter.class}##{method}' method is required."
  end
end

Instance Method Details

#within_limit(&block) ⇒ Object



62
63
64
65
66
# File 'lib/erp_integration/rate_limiter.rb', line 62

def within_limit(&block)
  ErpIntegration.config.logger.with_tags(@rate_limiter.name) do
    @rate_limiter.within_limit(&block)
  end
end