Class: VelocityCheck

Inherits:
Object
  • Object
show all
Defined in:
lib/velocity_check.rb,
lib/velocity_check/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ VelocityCheck

Returns a new instance of VelocityCheck.

Raises:

  • (ArgumentError)


4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/velocity_check.rb', line 4

def initialize(options)
  raise ArgumentError, ":name is required" unless options[:name]
  raise ArgumentError, ":name must only contain letters, numbers, and underscore" unless options[:name] =~ /\A\w+\z/
  raise ArgumentError, ":limit is required" unless options[:limit]
  raise ArgumentError, ":time_period is required" unless options[:time_period]
  raise ArgumentError, ":client is required" unless options[:client]

  known_options = [:name, :limit, :time_period, :client]
  unknown_options = options.keys - known_options
  raise ArgumentError, "Unknown options: #{unknown_options.map(&:to_s).sort.join(', ')}"  unless unknown_options.empty?

  @name = options[:name]
  @client = options[:client]
  @time_period = options[:time_period]
  @limit = options[:limit]
end

Instance Method Details

#check(key) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/velocity_check.rb', line 21

def check(key)
  full_key = "#{@name}_#{key}"

  # It would nice if we could incr + touch, but touch is buggy
  # in most versions of memcached (and doesn't even exist in
  # debian squeeze's version).
  previous = @client.get(full_key) || 0
  @client.set(full_key, previous + 1, @time_period)

  previous >= @limit
rescue Dalli::RingError
  false
end