Class: AggregateRoot::Repository

Inherits:
Object
  • Object
show all
Defined in:
lib/aggregate_root/repository.rb

Instance Method Summary collapse

Constructor Details

#initialize(event_store = default_event_store) ⇒ Repository

Returns a new instance of Repository.



5
6
7
# File 'lib/aggregate_root/repository.rb', line 5

def initialize(event_store = default_event_store)
  @event_store = event_store
end

Instance Method Details

#load(aggregate, stream_name) ⇒ Object



9
10
11
12
13
# File 'lib/aggregate_root/repository.rb', line 9

def load(aggregate, stream_name)
  event_store.read.stream(stream_name).reduce { |_, ev| aggregate.apply(ev) }
  aggregate.version = aggregate.unpublished_events.count - 1
  aggregate
end

#store(aggregate, stream_name) ⇒ Object



15
16
17
18
19
20
21
22
# File 'lib/aggregate_root/repository.rb', line 15

def store(aggregate, stream_name)
  event_store.publish(
    aggregate.unpublished_events.to_a,
    stream_name: stream_name,
    expected_version: aggregate.version
  )
  aggregate.version = aggregate.version + aggregate.unpublished_events.count
end

#with_aggregate(aggregate, stream_name, &block) ⇒ Object



24
25
26
27
# File 'lib/aggregate_root/repository.rb', line 24

def with_aggregate(aggregate, stream_name, &block)
  block.call(load(aggregate, stream_name))
  store(aggregate, stream_name)
end