Module: Mongo::Locking::ModelMethods::InstanceMethods

Defined in:
lib/mongo/locking/model_methods.rb

Overview

ClassMethods

Instance Method Summary collapse

Instance Method Details

#lock(opts = {}) ⇒ Object

Main closure-based lock method. opts remains present for future utility.



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/mongo/locking/model_methods.rb', line 64

def lock(opts = {})
    raise ArgumentError, "#{self.class.name}#lock requires a block" unless block_given?

    # Look for the top level lockable
    lockable = self.class.locker.root_for(self)

    # Try to acquire the lock. If succeeds, "locked" will be set
    locked = lockable.class.locker.acquire(lockable)

    return yield

rescue => e
    Locking.error "#{self.class.name}#lock failed"
    raise e

ensure
    # Only unlock if "locked" was set.  We're using this to
    # distinguish between an exception from the yield vs. an
    # exception from our own locking code.  Doing it in an
    # ensure block makes us defensible against a return from
    # within the closure, too.
    #
    # Calling lockable's locker instead of self potentially
    # saves us the cost of "find root lockable" that locker
    # would perform.
    lockable.class.locker.release(lockable) if locked
end