Skip to content

Instantly share code, notes, and snippets.

@deploy2
Forked from trans/dci1.rb
Created February 11, 2010 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save deploy2/302016 to your computer and use it in GitHub Desktop.
Save deploy2/302016 to your computer and use it in GitHub Desktop.
# 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