Created
April 17, 2020 14:35
-
-
Save sergueif/515b481b8409b6b1af025b21a5937a83 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Services | |
class UserService | |
#command is an "ActiveModel" | |
def apply_command(user_id, command) | |
aggregate = UserAggregate.find_or_create_by_id!(user_id) | |
aggregate.with_lock do | |
user = user_value(aggregate) | |
event = command.apply(user) | |
new_user = event.apply(user) | |
aggregate.version += 1 | |
aggregate.events << Event.new(event_type: event.class.to_s, body: event.to_h, version: aggregate.version) | |
aggregate.body = new_user.to_h | |
aggregate.save! | |
end | |
end | |
private | |
def user_value(aggregate) | |
user = Values::UserValue.new | |
events = Event.where(aggregate_id: aggregate).order(:version) | |
events.each do |e| | |
user = e.event_type.constantize.new(**e.body.symbolize_keys).apply(user) | |
end | |
user | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment