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



44
45
46
# File 'lib/ruby_event_store/projection.rb', line 44

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

#current_stateObject



40
41
42
# File 'lib/ruby_event_store/projection.rb', line 40

def current_state
  @current_state ||= initial_state
end

#handled_eventsObject



48
49
50
# File 'lib/ruby_event_store/projection.rb', line 48

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



36
37
38
# File 'lib/ruby_event_store/projection.rb', line 36

def initial_state
  @init.call
end

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



52
53
54
55
# File 'lib/ruby_event_store/projection.rb', line 52

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

#when(events, handler) ⇒ Object



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

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

  self
end