-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbalance.rb
43 lines (32 loc) · 869 Bytes
/
balance.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
require "aggregate_root"
require "ruby_event_store/event"
class Balance
include AggregateRoot
Credited = Class.new(RubyEventStore::Event)
Withdrawn = Class.new(RubyEventStore::Event)
Snapshot = Class.new(RubyEventStore::Event)
InsufficientFunds = Class.new(StandardError)
def initialize
@amount = 0
end
def credit(amount)
apply(Credited.new(data: { amount: amount }))
end
def withdraw(amount)
raise InsufficientFunds if @amount < amount
apply(Withdrawn.new(data: { amount: amount }))
end
def __snapshot_event__
Snapshot.new(data: { amount: @amount, version: @version })
end
on Credited do |event|
@amount += event.data[:amount]
end
on Withdrawn do |event|
@amount -= event.data[:amount]
end
on Snapshot do |event|
@amount = event.data[:amount]
@version = event.data[:version]
end
end