Module: Redis::Objects::Locks::ClassMethods

Defined in:
lib/redis/objects/locks.rb

Overview

Class methods that appear in your class when you include Redis::Objects.

Instance Method Summary collapse

Instance Method Details

#clear_lock(name, id) ⇒ Object

Clear the lock. Use with care - usually only in an Admin page to clear stale locks (a stale lock should only happen if a server crashes.)



58
59
60
61
# File 'lib/redis/objects/locks.rb', line 58

def clear_lock(name, id)
  verify_lock_defined!(name)
  redis.del(redis_field_key("#{name}_lock", id))
end

#lock(name, options = {}) ⇒ Object

Define a new lock. It will function like a model attribute, so it can be used alongside ActiveRecord/DataMapper, etc.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/redis/objects/locks.rb', line 17

def lock(name, options={})
  options[:timeout] ||= 5  # seconds
  lock_name = "#{name}_lock"
  redis_objects[lock_name.to_sym] = options.merge(:type => :lock)
  ivar_name = :"@#{lock_name}"

  mod = Module.new do
    define_method(lock_name) do |&block|
      instance_variable_get(ivar_name) or
        instance_variable_set(ivar_name,
          Redis::Lock.new(
            redis_field_key(lock_name), redis_field_redis(lock_name), redis_objects[lock_name.to_sym]
          )
        )
    end
  end

  if options[:global]
    extend mod

    # dispatch to class methods
    define_method(lock_name) do |&block|
      self.class.public_send(lock_name, &block)
    end
  else
    include mod
  end
end

#obtain_lock(name, id, &block) ⇒ Object

Obtain a lock, and execute the block synchronously. Any other code (on any server) will spin waiting for the lock up to the :timeout that was specified when the lock was defined.

Raises:

  • (ArgumentError)


49
50
51
52
53
54
# File 'lib/redis/objects/locks.rb', line 49

def obtain_lock(name, id, &block)
  verify_lock_defined!(name)
  raise ArgumentError, "Missing block to #{self.name}.obtain_lock" unless block_given?
  lock_name = "#{name}_lock"
  Redis::Lock.new(redis_field_key(lock_name, id), redis_field_redis(lock_name), redis_objects[lock_name.to_sym]).lock(&block)
end