module ActionThrottling::InstanceMethods
Public Instance Methods
cost(price)
click to toggle source
# 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 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 update_call_time end
Private Instance Methods
bucket_key()
click to toggle source
# File lib/action_throttling.rb, line 57 def bucket_key instance_eval &ActionThrottling.configuration.bucket_key end
expired?()
click to toggle source
# File lib/action_throttling.rb, line 32 def expired? last_called < regeneration_time end
last_call_key()
click to toggle source
# File lib/action_throttling.rb, line 36 def last_call_key "#{bucket_key}-last-call" end
last_called()
click to toggle source
# File lib/action_throttling.rb, line 48 def last_called value = redis.get(last_call_key).presence # trigger regeneration when first cost is first called value ||= (regeneration_time - 1.second).httpdate Time.parse value end
redis()
click to toggle source
# File lib/action_throttling.rb, line 65 def redis @redis ||= ActionThrottling.configuration.redis end
regenerate()
click to toggle source
# File lib/action_throttling.rb, line 40 def regenerate redis.set bucket_key, regenerate_amount end
regenerate_amount()
click to toggle source
# File lib/action_throttling.rb, line 44 def regenerate_amount instance_eval &ActionThrottling.configuration.regenerate_amount end
regeneration_time()
click to toggle source
# File lib/action_throttling.rb, line 61 def regeneration_time instance_eval(&ActionThrottling.configuration.regenerate_interval).ago end
update_call_time()
click to toggle source
# File lib/action_throttling.rb, line 28 def update_call_time redis.set last_call_key, Time.now.httpdate end