Class: Midnight::Mongoid::State

Inherits:
Object
  • Object
show all
Includes:
Mongoid::Document
Defined in:
lib/midnight/mongoid/state.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.load(key:, **_) ⇒ Object



52
53
54
55
56
57
58
59
# File 'lib/midnight/mongoid/state.rb', line 52

def load(key:, **_)
  where(
    _id: key
  ).first_or_create!
rescue ::Mongo::Error::OperationFailure => e
  raise e unless e.code == 11000
  retry
end

Instance Method Details

#advance_metadata(events) ⇒ Object



23
24
25
# File 'lib/midnight/mongoid/state.rb', line 23

def (events)
  self.next_position += events.length
end

#metadataObject



15
16
17
18
19
20
21
# File 'lib/midnight/mongoid/state.rb', line 15

def 
  {
    next_position: next_position,
    state_id: _id,
    aggregate_key: _id,
  }
end

#save!Object

Raises:



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/midnight/mongoid/state.rb', line 32

def save!
  return true unless @state_changed
  raise StaleObjectError unless _id.present?
  update_result = collection.update_one({
    _id: _id,
    lock_version: self.lock_version,
  }.with_indifferent_access, {
    '$set': {
      state: self.state,
      next_position: self.next_position,
    }.compact,
    '$inc': {
      lock_version: 1
    }
  }.with_indifferent_access)
  raise StaleObjectError if update_result.matched_count < 1
  !!(self.lock_version += 1)
end

#state=(new_state) ⇒ Object



27
28
29
30
# File 'lib/midnight/mongoid/state.rb', line 27

def state=(new_state)
  @state_changed = true
  super(new_state)
end