lib/action_throttling.rb in rails-action_throttling-0.1.1 vs lib/action_throttling.rb in rails-action_throttling-0.1.2
- old
+ new
@@ -9,32 +9,44 @@
module InstanceMethods
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
+ regenerate if expired?
# 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
+ update_call_time
end
private
+ def update_call_time
+ redis.set last_call_key, Time.now.httpdate
+ end
+
+ def expired?
+ last_called < regeneration_time
+ end
+
def last_call_key
"#{bucket_key}-last-call"
end
def regenerate
- redis.set bucket_key, ActionThrottling.configuration.regenerate_amount
+ redis.set bucket_key, regenerate_amount
end
+ def regenerate_amount
+ instance_eval &ActionThrottling.configuration.regenerate_amount
+ end
+
def last_called
value = redis.get(last_call_key).presence
# trigger regeneration when first cost is first called
value ||= (regeneration_time - 1.second).httpdate
@@ -45,10 +57,10 @@
def bucket_key
instance_eval &ActionThrottling.configuration.bucket_key
end
def regeneration_time
- ActionThrottling.configuration.regenerate_interval.ago
+ instance_eval(&ActionThrottling.configuration.regenerate_interval).ago
end
def redis
@redis ||= ActionThrottling.configuration.redis
end