Last active
August 29, 2015 13:58
-
-
Save phillipoertel/9964249 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
class Account | |
def initialize(id) | |
@balance = 0 | |
@id = id | |
end | |
def decrease_balance(amount) | |
@balance -= amount | |
end | |
def increase_balance(amount) | |
@balance += amount | |
end | |
def to_s | |
"Account ##{@id} balance: #{@balance}" | |
end | |
end | |
module ContextAccessor | |
def context | |
Thread.current[:context] | |
end | |
def context=(ctx) | |
Thread.current[:context] = ctx | |
end | |
def execute_in_context | |
old = self.context | |
self.context = self | |
yield | |
self.context = old | |
end | |
end | |
module MoneySourceRole | |
include ContextAccessor | |
def transfer_to | |
# begin_transaction | |
#raise "Insuffictent funds" if ... | |
self.decrease_balance(context.amount) | |
context.destination_account.transfer_from | |
# log ... | |
# end_transaction | |
end | |
end | |
module MoneySinkRole | |
include ContextAccessor | |
def transfer_from | |
self.increase_balance(context.amount) | |
# log ... | |
end | |
end | |
class MoneyTransferContext | |
include ContextAccessor | |
attr_accessor :source_account, :destination_account, :amount | |
def initialize(source_id, destination_id, amount) | |
self.source_account = Account.new(source_id) | |
self.source_account.extend MoneySourceRole | |
self.destination_account = Account.new(destination_id) | |
self.destination_account.extend MoneySinkRole | |
self.amount = amount | |
end | |
def perform | |
execute_in_context { source_account.transfer_to } | |
puts source_account | |
puts destination_account | |
end | |
end | |
context = MoneyTransferContext.new(1, 2, 100) | |
context.perform |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment