Class: Lyra::Associations::EventReconstructor

Inherits:
Object
  • Object
show all
Defined in:
lib/lyra/associations/event_aware.rb

Overview

Reconstructs a record from its event stream

Class Method Summary collapse

Class Method Details

.reconstruct(model_class, id) ⇒ VirtualRecord?

Reconstruct a record's current state from events

Parameters:

  • model_class (Class) —

    The model class

  • id (Integer, String) —

    The record ID

Returns:

  • (VirtualRecord, nil) —

    A virtual record or nil if not found/deleted



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/lyra/associations/event_aware.rb', line 93

def reconstruct(model_class, id)
  stream_name = "#{model_class.name}$#{id}"

  begin
    events = Lyra.config.event_store.read.stream(stream_name).to_a
  rescue StandardError
    return nil
  end

  return nil if events.empty?

  # Replay events to build current state
  state = replay_events(events)

  return nil if state[:deleted]

  VirtualRecord.new(model_class, id, state)
end