-
Notifications
You must be signed in to change notification settings - Fork 0
/
money_transfer.rb
48 lines (40 loc) · 1.17 KB
/
money_transfer.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
module Funds
Insufficient = Class.new(StandardError)
module SourceAccount
def decrease_balance_by(amount)
fail Funds::Insufficient, "Balance is below amount.", caller if balance < amount
self.balance -= amount
end
end
module DestinationAccount
def increase_balance_by(amount)
self.balance += amount
end
end
module Logging
def log(transfer_type, amount, account, at: Time.now)
self << [transfer_type, account.number, amount, at]
end
end
class TransferMoney < DCI::Context(:amount, from: SourceAccount, to: DestinationAccount, events: Logging)
def initialize(amount: 0, events: [], **accounts) super end
def withdraw(amount)
from.decrease_balance_by(amount)
events.log "Withdrew", amount, @from
end
def deposit(amount)
to.increase_balance_by(amount)
events.log "Deposited", amount, @to
end
def transfer(amount)
withdraw(amount)
deposit(amount)
end
def call(amount: @amount)
transfer(amount)
return :success, logging: @events, accounts: [@from, @to]
rescue Funds::Insufficient => error
return :failure, message: error.message
end
end
end