Module: Mongoid::Locker

Defined in:
lib/mongoid/locker.rb,
lib/mongoid/locker/wrapper4.rb,
lib/mongoid/locker/wrapper2.rb,
lib/mongoid/locker/wrapper5.rb,
lib/mongoid/locker/wrapper3.rb

Defined Under Namespace

Modules: ClassMethods, Wrapper Classes: LockError

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(mod) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.


41
42
43
44
45
46
# File 'lib/mongoid/locker.rb', line 41

def self.included(mod)
  mod.extend ClassMethods

  mod.field :locked_at, type: Time
  mod.field :locked_until, type: Time
end

Instance Method Details

#has_lock?Boolean

Returns whether the current instance has the lock or not.


58
59
60
# File 'lib/mongoid/locker.rb', line 58

def has_lock?
  !!(@has_lock && self.locked?)
end

#locked?Boolean

Returns whether the document is currently locked or not.


51
52
53
# File 'lib/mongoid/locker.rb', line 51

def locked?
  !!(locked_until && locked_until > Time.now)
end

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

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 (note: setting this to 1 is the equivalent of using :wait => true)

  • :retry_sleep (Float)

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

  • :wait (Boolean)

    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


71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/mongoid/locker.rb', line 71

def with_lock(opts = {})
  have_lock = self.has_lock?

  unless have_lock
    opts[:retries] = 1 if opts[:wait]
    lock(opts)
  end

  begin
    yield
  ensure
    unlock unless have_lock
  end
end