lib/redis-throttler/model.rb in redis-throttler-0.1.5 vs lib/redis-throttler/model.rb in redis-throttler-0.1.6
- old
+ new
@@ -16,32 +16,34 @@
subject = opts[:by] || :id
limit = opts[:limit] || 5
threshold = opts[:for] || 900
interval = opts[:interval] || 5
- limiter = RedisThrottler::Base.new("#{klass}:#{key}", bucket_interval: interval, bucket_span: threshold)
+ bucket_span = [interval, 600].max
+
+ throttler = RedisThrottler::Base.new("#{klass}:#{key}", bucket_interval: interval, bucket_span: bucket_span)
@limits[key] = "#{subject.to_s} limit #{limit} per #{threshold} sec"
# includes('?') will return true
- method = "#{key}_limiter"
+ method = "#{key}_throttler"
%w(limits limits?).each do |string|
define_singleton_method(string) { string.include?('?') || @limits }
- define_method(string) { string.include?('?') || @limits }
+ define_method(string) { string.include?('?') || self.class.instance_variable_get('@limits')}
end
# i used Procs because they don't complain about arity
# these Procs will return a string to be evaluated in context
methods = {
- :exceeded? => proc { |to_call| "#{method}.exceeded? \"#{to_call}\", threshold: #{limit}, interval: #{threshold}" },
+ :exceeded? => proc { |to_call, within| "#{method}.exceeded? \"#{to_call}\", threshold: #{limit}, interval: #{within}" },
:increment => proc { |to_call| "#{method}.add(\"#{to_call}\")" },
:count => proc { |to_call, within| "#{method}.count(\"#{to_call}\", #{within})" }
}
# define the class & instance methods
# pass the id to access counters
- define_singleton_method(method) { limiter }
+ define_singleton_method(method) { throttler }
define_method(method) { self.class.send method }
methods.each do |magic, meth|
define_singleton_method("#{key}_#{magic.to_s}") { |id, within = threshold| eval meth.call(id, within) }
define_method("#{key}_#{magic.to_s}") { |within = threshold| eval meth.call("#{self.send subject}", within) }
\ No newline at end of file