Class: SimpleRateLimiter::Service

Inherits:
Object
  • Object
show all
Includes:
Domain
Defined in:
lib/simple_rate_limiter.rb

Instance Method Summary collapse

Constructor Details

#initialize(record_repository) ⇒ Service

Returns a new instance of Service.



10
11
12
13
# File 'lib/simple_rate_limiter.rb', line 10

def initialize(record_repository)
  @record_repository = record_repository
  @violation_repository = SimpleRateLimiter::Repositories::ViolationRepository.new(record_repository)
end

Instance Method Details

#check(route_name, user_id, rate_limit, limit_period, punishment_factor) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/simple_rate_limiter.rb', line 15

def check(route_name, user_id, rate_limit, limit_period, punishment_factor)
  limiter = Domain::Limiter.new(route_name, user_id, rate_limit, punishment_factor, limit_period)
  identifier = limiter.identifier
  @record_repository.add(identifier)
  @record_repository.trim_by_name(identifier, rate_limit)

  violation_records = @violation_repository.get_all(identifier)

  return true if limiter.was_violated?(violation_records)

  @violation_repository.remove_last(identifier) if limiter.violation_expired?(violation_records)

  records = @record_repository.get_by_name(identifier, rate_limit)

  if limiter.rate_violated?(records)
    @violation_repository.add(identifier)
    return true
  end

  false
end