Skip to content

Instantly share code, notes, and snippets.

@vsavkin
Created August 12, 2012 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vsavkin/3333675 to your computer and use it in GitHub Desktop.
Save vsavkin/3333675 to your computer and use it in GitHub Desktop.
Context & Roles
class TransferringMoney
include Context
def self.transfer source_account_id, destination_account_id, amount
source = Account.find(source_account_id)
destination = Account.find(destination_account_id)
TransferringMoney.new(source, destination).transfer amount
end
attr_reader :source_account, :destination_account
def initialize source_account, destination_account
@source_account = source_account.extend SourceAccount
@destination_account = destination_account.extend DestinationAccount
end
def transfer amount
in_context do
source_account.transfer_out amount
end
end
module SourceAccount
include ContextAccssor
def transfer_out amount
raise "Insufficient funds" if balance < amount
decrease_balance amount
context.destination_account.transfer_in amount
update_log "Transferred out", amount
end
end
module DestinationAccount
include ContextAccssor
def transfer_in amount
increase_balance amount
update_log "Transferred in", amount
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment