lib/mongoid/locker.rb in mongoid-locker-1.0.0 vs lib/mongoid/locker.rb in mongoid-locker-1.0.1
- old
+ new
@@ -106,27 +106,29 @@
# Primary method of plugin: execute the provided code once the document has been successfully locked.
#
# @param [Hash] opts for the locking mechanism
# @option opts [Fixnum] :timeout The number of seconds until the lock is considered "expired" - defaults to the {ClassMethods#lock_timeout}
- # @option opts [Fixnum] :retries If the document is currently locked, the number of times to retry. Defaults to 0 (note: setting this to 1 is the equivalent of using :wait => true)
+ # @option opts [Fixnum] :retries If the document is currently locked, the number of times to retry - defaults to 0
# @option opts [Float] :retry_sleep How long to sleep between attempts to acquire lock - defaults to time left until lock is available
- # @option opts [Boolean] :wait If the document is currently locked, wait until the lock expires and try again - defaults to false. If set, :retries will be ignored
+ # @option opts [Boolean] :wait (deprecated) If the document is currently locked, wait until the lock expires and try again - defaults to false. If set, :retries will be ignored
# @option opts [Boolean] :reload After acquiring the lock, reload the document - defaults to true
# @return [void]
def with_lock(opts = {})
- had_lock = has_lock?
+ unless !persisted? || (had_lock = has_lock?)
+ if opts[:wait]
+ opts[:retries] = 1
+ warn 'WARN: `:wait` option for Mongoid::Locker is deprecated - use `retries: 1` instead.'
+ end
- unless had_lock
- opts[:retries] = 1 if opts[:wait]
lock(opts)
end
begin
yield
ensure
- unlock if locked? && !had_lock
+ unlock if !had_lock && locked?
end
end
protected
@@ -173,22 +175,21 @@
loop do
return if acquire_lock(opts)
attempts_left -= 1
- if attempts_left > 0
- # if not passed a retry_sleep value, we sleep for the remaining life of the lock
- unless retry_sleep
- locked_until = Mongoid::Locker::Wrapper.locked_until(self)
- # the lock might be released since the last check so make another attempt
- next unless locked_until
- retry_sleep = locked_until - Time.now.utc
- end
+ raise LockError, 'could not get lock' unless attempts_left > 0
- sleep retry_sleep if retry_sleep > 0
- else
- raise LockError.new('could not get lock')
+ # if not passed a retry_sleep value, we sleep for the remaining life of the lock
+ unless retry_sleep
+ locked_until = Mongoid::Locker::Wrapper.locked_until(self)
+ # the lock might be released since the last check so make another attempt
+ next unless locked_until
+
+ retry_sleep = locked_until - Time.now.utc
end
+
+ sleep retry_sleep if retry_sleep > 0
end
end
def unlock
# unlock the document in the DB without persisting entire doc