lib/redis/objects/locks.rb in redis-objects-0.7.0 vs lib/redis/objects/locks.rb in redis-objects-0.8.0
- old
+ new
@@ -16,27 +16,30 @@
# so it can be used alongside ActiveRecord/DataMapper, etc.
def lock(name, options={})
options[:timeout] ||= 5 # seconds
lock_name = "#{name}_lock"
redis_objects[lock_name.to_sym] = options.merge(:type => :lock)
- klass_name = '::' + self.name
+
+ 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, redis_objects[lock_name.to_sym]
+ )
+ )
+ end
+ end
+
if options[:global]
- instance_eval <<-EndMethods
- def #{lock_name}(&block)
- @#{lock_name} ||= Redis::Lock.new(redis_field_key(:#{lock_name}), #{klass_name}.redis, #{klass_name}.redis_objects[:#{lock_name}])
- end
- EndMethods
- class_eval <<-EndMethods
- def #{lock_name}(&block)
- self.class.#{lock_name}(block)
- end
- EndMethods
+ extend mod
+
+ # dispatch to class methods
+ define_method(lock_name) do |&block|
+ self.class.public_send(lock_name, &block)
+ end
else
- class_eval <<-EndMethods
- def #{lock_name}(&block)
- @#{lock_name} ||= Redis::Lock.new(redis_field_key(:#{lock_name}), #{klass_name}.redis, #{klass_name}.redis_objects[:#{lock_name}])
- end
- EndMethods
+ include mod
end
end
# Obtain a lock, and execute the block synchronously. Any other code
# (on any server) will spin waiting for the lock up to the :timeout