Skip to content

Instantly share code, notes, and snippets.

@mariuszkapcia
Last active January 28, 2019 17:45
Show Gist options
  • Save mariuszkapcia/e0ba0a0707bdc0e47380a0fafb1181b7 to your computer and use it in GitHub Desktop.
Save mariuszkapcia/e0ba0a0707bdc0e47380a0fafb1181b7 to your computer and use it in GitHub Desktop.
AggregateRoot pattern with apply_strategy methods.
module MyAggregateRoot
MissingEventInApplyStrategy = Class.new(StandardError)
def load(stream_name, event_store:)
@version = -1
event_store.read.stream(stream_name).forward.each do |event|
apply(event)
@version += 1
end
@stream_name = stream_name
@unpublished_events = []
end
def default_apply_strategy(event)
"apply_#{event.class.to_s.demodulize.underscore}"
end
def apply_strategy
{}
end
def apply(event)
mutate_state(event)
unpublished_events.push(event)
end
def mutate_state(event)
begin
callback_method = if apply_strategy.present?
apply_strategy.fetch(event.class.to_s.demodulize.underscore.to_sym)
else
default_apply_strategy(event)
end
rescue KeyError
raise MissingEventInApplyStrategy.new("#{event.class} is missing in apply_strategy.")
end
send(callback_method, event)
end
def store(event_store:)
unpublished_events.each do |event|
event_store.publish(
event,
stream_name: @stream_name,
expected_version: version
)
@version += 1
end
@unpublished_events = []
end
def unpublished_events
@unpublished_events ||= []
end
def version
@version ||= -1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment