Module: Mongoid::OptimisticLocking::Operations

Included in:
Mongoid::OptimisticLocking
Defined in:
lib/mongoid/optimistic_locking/operations.rb

Instance Method Summary collapse

Instance Method Details

#atomic_selectorObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/mongoid/optimistic_locking/operations.rb', line 38

def atomic_selector
  result = super
  if optimistic_locking? && lock_version_for_selector
    key =
      if  && .embedded?
        path = .path(self)
        "#{path.path}._lock_version"
      else
        '_lock_version'
      end
    result[key] = lock_version_for_selector
  end
  result
end

#insert(options = {}) ⇒ Object



5
6
7
8
9
10
# File 'lib/mongoid/optimistic_locking/operations.rb', line 5

def insert(options = {})
  return super unless optimistic_locking? && valid?
  increment_lock_version do
    super
  end
end

#remove(options = {}) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/mongoid/optimistic_locking/operations.rb', line 26

def remove(options = {})
  return super unless optimistic_locking? && persisted?
  # we need to just see if the document exists and got updated with
  # a higher lock version
  existing = _reload # get the current root or embedded document
  if existing.present? && existing['_lock_version'] &&
     existing['_lock_version'].to_i > _lock_version.to_i
    raise Mongoid::Errors::StaleDocument.new('destroy', self)
  end
  super
end

#update(options = {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/mongoid/optimistic_locking/operations.rb', line 12

def update(options = {})
  return super unless optimistic_locking? && valid?
  set_lock_version_for_selector do
    increment_lock_version do
      result = super
      getlasterror = mongo_session.command({:getlasterror => 1})
      if result && !getlasterror['updatedExisting']
        raise Mongoid::Errors::StaleDocument.new('update', self)
      end
      result
    end
  end
end