class Grape::Attack::Limiter

Attributes

adapter[R]
counter[R]
request[R]

Public Class Methods

new(env, adapter = ::Grape::Attack.config.adapter) click to toggle source
# File lib/grape/attack/limiter.rb, line 10
def initialize(env, adapter = ::Grape::Attack.config.adapter)
  @request = ::Grape::Attack::Request.new(env)
  @adapter = adapter
  @counter = ::Grape::Attack::Counter.new(@request, @adapter)
end

Public Instance Methods

call!() click to toggle source
# File lib/grape/attack/limiter.rb, line 16
def call!
  return if disable?
  return unless throttle?

  if allowed?
    update_counter
    set_rate_limit_headers
  else
    fail ::Grape::Attack::RateLimitExceededError.new("API rate limit exceeded for #{request.client_identifier}.")
  end
end

Private Instance Methods

allowed?() click to toggle source
# File lib/grape/attack/limiter.rb, line 38
def allowed?
  counter.value < max_requests_allowed
end
disable?() click to toggle source
# File lib/grape/attack/limiter.rb, line 30
def disable?
  ::Grape::Attack.config.disable.call
end
max_requests_allowed() click to toggle source
# File lib/grape/attack/limiter.rb, line 50
def max_requests_allowed
  request.throttle_options.max.to_i
end
set_rate_limit_headers() click to toggle source
# File lib/grape/attack/limiter.rb, line 46
def set_rate_limit_headers
  request.context.route_setting(:throttle)[:remaining] = [0, max_requests_allowed - (counter.value + 1)].max
end
throttle?() click to toggle source
# File lib/grape/attack/limiter.rb, line 34
def throttle?
  request.throttle?
end
update_counter() click to toggle source
# File lib/grape/attack/limiter.rb, line 42
def update_counter
  counter.update
end