-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbalance.rb
48 lines (36 loc) · 1.01 KB
/
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
44
45
46
47
48
require "aggregate_root"
require "ruby_event_store/event"
class Balance
include AggregateRoot
Credited = Class.new(RubyEventStore::Event)
Withdrawn = 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
on Credited do |event|
@amount += event.data[:amount]
end
on Withdrawn do |event|
@amount -= event.data[:amount]
end
UNMARSHALED_VARIABLES = [:@version, :@unpublished_events]
def marshal_dump
instance_variables.reject{|m| UNMARSHALED_VARIABLES.include? m}.inject({}) do |vars, attr|
vars[attr] = instance_variable_get(attr)
vars
end
end
def marshal_load(vars)
vars.each do |attr, value|
instance_variable_set(attr, value) unless UNMARSHALED_VARIABLES.include?(attr)
end
end
end