Class: EventSorcerer::UnitOfWork

Inherits:
Object
  • Object
show all
Extended by:
Uber::Delegates
Defined in:
lib/event_sorcerer/unit_of_work.rb

Overview

Public: Provides transactional integrity across multiple aggregate saves.

Also provides an indentity map.

Instance Method Summary collapse

Constructor Details

#initializeUnitOfWork

Public: Creates a new UnitOfWork instance.



11
12
13
14
15
# File 'lib/event_sorcerer/unit_of_work.rb', line 11

def initialize
  @identity_map  = {}
  @meta          = {}
  @pending_saves = []
end

Instance Method Details

#add_meta_data(meta_hash) ⇒ Object

Public: Add additional meta data to be sent along with any save reciepts

on the message bus for the duration of the unit of work.


19
20
21
# File 'lib/event_sorcerer/unit_of_work.rb', line 19

def (meta_hash)
  meta.merge! meta_hash
end

#execute_work!Object

Public: Executes all pending saves within a transaction, clears the

pending saves, and publishes the reciepts via the message bus.

Returns self.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/event_sorcerer/unit_of_work.rb', line 27

def execute_work!
  save_receipts = event_store.with_transaction do
    pending_saves.map(&:call)
  end

  @pending_saves = []

  save_receipts.each do |reciept|
    message_bus.publish_events(reciept.id, reciept.klass, reciept.events,
                               reciept.meta.merge(meta))
  end

  self
end

#fetch_aggregate(type, id) ⇒ Object

Public: Fetches an aggregate via it’s ID from the identity map.

type - the type for the aggregate. id - the ID for the aggregate.

Returns nil if not found. Returns Aggregate if found.



49
50
51
52
53
# File 'lib/event_sorcerer/unit_of_work.rb', line 49

def fetch_aggregate(type, id)
  return unless identity_map[type]

  identity_map[type][id]
end

#handle_save(save) ⇒ Object



55
56
57
58
59
# File 'lib/event_sorcerer/unit_of_work.rb', line 55

def handle_save(save)
  pending_saves << save

  self
end

#store_aggregate(aggregate) ⇒ Object

Public: Stores an aggregate via it’s ID into the identity map.

aggregate - the aggregate to store.

Returns self.



66
67
68
69
70
71
72
# File 'lib/event_sorcerer/unit_of_work.rb', line 66

def store_aggregate(aggregate)
  type = aggregate.class.to_s
  identity_map[type] ||= {}
  identity_map[type][aggregate.id] = aggregate

  self
end