Method: Mongoid::Locker#with_lock

Defined in:
lib/mongoid/locker.rb

#with_lock(opts = {}) ⇒ void

This method returns an undefined value.

Primary method of plugin: execute the provided code once the document has been successfully locked.

Parameters:

  • opts (Hash) (defaults to: {})

    for the locking mechanism

Options Hash (opts):

  • :timeout (Fixnum)

    The number of seconds until the lock is considered “expired” - defaults to the Mongoid::Locker::ClassMethods#lock_timeout

  • :retries (Fixnum)

    If the document is currently locked, the number of times to retry - defaults to 0

  • :retry_sleep (Float)

    How long to sleep between attempts to acquire lock - defaults to time left until lock is available

  • :wait (Boolean) — default: deprecated

    If the document is currently locked, wait until the lock expires and try again - defaults to false. If set, :retries will be ignored

  • :reload (Boolean)

    After acquiring the lock, reload the document - defaults to true


116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/mongoid/locker.rb', line 116

def with_lock(opts = {})
  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

    lock(opts)
  end

  begin
    yield
  ensure
    unlock if !had_lock && locked?
  end
end