Module: ActionThrottling::InstanceMethods

Defined in:
lib/action_throttling.rb

Instance Method Summary collapse

Instance Method Details

#cost(price) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/action_throttling.rb', line 11

def cost(price)
  # If last time the bucket was called is older than the regeneration limit
  # regenerate the bucket.
  regenerate if last_called < regeneration_time

  # Deduct the price from the bucket. If it's below zero we raiss a
  # HttpError::ToManyRequests exception/
  if redis.decrby(bucket_key, price) < 0
    raise HttpError::ToManyRequests, "Throttling enabled. Please try again later"
  end

  # Store when the cost was last called so we can calculate regeneration
  redis.set last_call_key, Time.now.httpdate
end