Class: RubyEventStore::Projection

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_event_store/projection.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(streams: []) ⇒ Projection

Returns a new instance of Projection.


17
18
19
20
21
# File 'lib/ruby_event_store/projection.rb', line 17

def initialize(streams: [])
  @streams  = streams
  @handlers = {}
  @init     = -> { {} }
end

Instance Attribute Details

#handlersObject (readonly)

Returns the value of attribute handlers.


23
24
25
# File 'lib/ruby_event_store/projection.rb', line 23

def handlers
  @handlers
end

#streamsObject (readonly)

Returns the value of attribute streams.


23
24
25
# File 'lib/ruby_event_store/projection.rb', line 23

def streams
  @streams
end

Class Method Details

.from_all_streamsObject


13
14
15
# File 'lib/ruby_event_store/projection.rb', line 13

def self.from_all_streams
  new
end

.from_stream(stream_or_streams) ⇒ Object

Raises:

  • (ArgumentError)

7
8
9
10
11
# File 'lib/ruby_event_store/projection.rb', line 7

def self.from_stream(stream_or_streams)
  streams = Array(stream_or_streams)
  raise(ArgumentError, "At least one stream must be given") if streams.empty?
  new(streams: streams)
end

Instance Method Details

#call(event) ⇒ Object


46
47
48
# File 'lib/ruby_event_store/projection.rb', line 46

def call(event)
  handlers.fetch(event.event_type).(current_state, event)
end

#current_stateObject


42
43
44
# File 'lib/ruby_event_store/projection.rb', line 42

def current_state
  @current_state ||= initial_state
end

#handled_eventsObject


50
51
52
# File 'lib/ruby_event_store/projection.rb', line 50

def handled_events
  handlers.keys
end

#init(handler) ⇒ Object


25
26
27
28
# File 'lib/ruby_event_store/projection.rb', line 25

def init(handler)
  @init = handler
  self
end

#initial_stateObject


38
39
40
# File 'lib/ruby_event_store/projection.rb', line 38

def initial_state
  @init.call
end

#run(event_store, start: nil, count: PAGE_SIZE) ⇒ Object


54
55
56
57
58
59
60
61
# File 'lib/ruby_event_store/projection.rb', line 54

def run(event_store, start: nil, count: PAGE_SIZE)
  return initial_state if handled_events.empty?
  if streams.any?
    reduce_from_streams(event_store, start, count)
  else
    reduce_from_all_streams(event_store, start, count)
  end
end

#when(events, handler) ⇒ Object


30
31
32
33
34
35
36
# File 'lib/ruby_event_store/projection.rb', line 30

def when(events, handler)
  Array(events).each do |event|
    handlers[event.to_s] = handler
  end

  self
end