-
-
Save deploy2/302016 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
# Role base class. Use SimpleDelegator instead? | |
class Role | |
def initialize(player) | |
@player = player | |
end | |
# should be public send ? | |
def method_missing(s, *a, &b) | |
@player.__send__(s, *a, &b) | |
end | |
end | |
# Context (UseCase) base class. | |
class Context | |
def cast(player, role) | |
role.new(player) | |
end | |
end | |
# --- example --- | |
# Mixins are fixed roles. | |
module Balance | |
def initialize | |
@balance = 0 | |
end | |
def availableBalance | |
@balance | |
end | |
def increaseBalance(amount) | |
@balance += amount | |
end | |
def decreaseBalance(amount) | |
@balance -= amount | |
end | |
end | |
# | |
class Balance::TransferSource < Role | |
def transfer(amount) | |
decreaseBalance(amount) | |
puts "Tranfered from account #{__id__} $#{amount}" | |
end | |
end | |
# | |
class Balance::TransferDestination < Role | |
def transfer(amount) | |
increaseBalance(amount) | |
puts "Tranfered to account #{__id__} $#{amount}" | |
end | |
end | |
# We can think of a context as setting a scene. | |
class Balance::Transfer < Context | |
attr_reader :source_account, :destination_account | |
def initialize(source_account, destination_account) | |
@source_account = cast(source_account, Balance::TransferSource) | |
@destination_account = cast(destination_account, Balance::TransferDestination) | |
end | |
def transfer(amount) | |
source_account.transfer(amount) | |
destination_account.transfer(amount) | |
end | |
end | |
class Account | |
# An account by definition has a balance. | |
include Balance | |
end | |
acct1 = Account.new | |
acct2 = Account.new | |
Balance::Transfer.new(acct1, acct2).transfer(50) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment