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 Attribute Summary collapse
-
#locks ⇒ Object
readonly
Returns the value of attribute locks.
Instance Method Summary collapse
-
#clear_lock(name, id) ⇒ Object
Clear the lock.
-
#lock(name, options = {}) ⇒ Object
Define a new lock.
-
#obtain_lock(name, id, &block) ⇒ Object
Obtain a lock, and execute the block synchronously.
Instance Attribute Details
#locks ⇒ Object (readonly)
Returns the value of attribute locks.
16 17 18 |
# File 'lib/redis/objects/locks.rb', line 16 def locks @locks end |
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.)
42 43 44 45 46 |
# File 'lib/redis/objects/locks.rb', line 42 def clear_lock(name, id) verify_lock_defined!(name) lock_name = field_key("#{name}_lock", id) redis.del(lock_name) 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.
20 21 22 23 24 25 26 27 28 |
# File 'lib/redis/objects/locks.rb', line 20 def lock(name, ={}) [:timeout] ||= 5 # seconds @locks[name] = class_eval <<-EndMethods def #{name}_lock(&block) @#{name}_lock ||= Redis::Lock.new(field_key(:#{name}_lock), redis, self.class.locks[:#{name}]) end EndMethods 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.
33 34 35 36 37 38 |
# File 'lib/redis/objects/locks.rb', line 33 def obtain_lock(name, id, &block) verify_lock_defined!(name) raise ArgumentError, "Missing block to #{self.name}.obtain_lock" unless block_given? lock_name = field_key("#{name}_lock", id) Redis::Lock.new(redis, lock_name, self.class.locks[name]).lock(&block) end |