Class: Lyra::StateProjection

Inherits:
Projection show all
Defined in:
lib/lyra/projection.rb

Overview

State projection that rebuilds current state from events

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Projection

handle, #handle, subscribe_to

Class Method Details

.rebuild_state(model_class, model_id) ⇒ Object



24
25
26
27
28
29
# File 'lib/lyra/projection.rb', line 24

def self.rebuild_state(model_class, model_id)
  stream_name = "#{model_class.name}$#{model_id}"
  events = Lyra.config.event_store.read.stream(stream_name).to_a

  new.rebuild_from_events(events)
end

Instance Method Details

#rebuild_from_events(events) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/lyra/projection.rb', line 31

def rebuild_from_events(events)
  state = {}

  events.each do |event|
    case event_operation(event)
    when :created
      state = event_attributes(event)
    when :updated
      state.merge!(event_changes(event).transform_values { |v| v.last })
    when :destroyed
      state[:deleted] = true
      state[:deleted_at] = event_timestamp(event)
    end
  end

  state
end