class Midnight::Mongoid::State

Public Class Methods

load(key:, **_) click to toggle source
# 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

Public Instance Methods

advance_metadata(events) click to toggle source
# File lib/midnight/mongoid/state.rb, line 23
def advance_metadata(events)
  self.next_position += events.length
end
metadata() click to toggle source
# File lib/midnight/mongoid/state.rb, line 15
def metadata
  {
    next_position: next_position,
    state_id: _id,
    aggregate_key: _id,
  }
end
save!() click to toggle source
# 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) click to toggle source
Calls superclass method
# File lib/midnight/mongoid/state.rb, line 27
def state=(new_state)
  @state_changed = true
  super(new_state)
end