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

- (Object) clear_lock(name, id)

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.)



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

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

- (Object) lock(name, options = {})

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
# 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)

  mod = Module.new do
    define_method(lock_name) do |&block|
      instance_variable_get("@#{lock_name}") or
        instance_variable_set("@#{lock_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

- (Object) obtain_lock(name, id, &block)

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)


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

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