Class: Rack::Ratelimit::MemcachedCounter

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/ratelimit.rb

Instance Method Summary collapse

Constructor Details

#initialize(cache, name, period) ⇒ MemcachedCounter

Returns a new instance of MemcachedCounter.



187
188
189
# File 'lib/rack/ratelimit.rb', line 187

def initialize(cache, name, period)
  @cache, @name, @period = cache, name, period
end

Instance Method Details

#increment(classification, epoch) ⇒ Object

Increment the request counter and return the current count.



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/rack/ratelimit.rb', line 192

def increment(classification, epoch)
  key = 'rack-ratelimit/%s/%s/%i' % [@name, classification, epoch]

  # Try to increment the counter if it's present.
  if count = @cache.incr(key, 1)
    count.to_i

  # If not, add the counter and set expiry.
  elsif @cache.add(key, 1, @period, :raw => true)
    1

  # If adding failed, someone else added it concurrently. Increment.
  else
    @cache.incr(key, 1).to_i
  end
rescue Dalli::DalliError
  0
end