Last active
December 11, 2015 04:38
-
-
Save runefs/4546002 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Context | |
| def bind(player, roleMethods) | |
| lambda {|(*args)| | |
| if args.length == 0 then return player end | |
| name = args[0] | |
| m = roleMethods[name] | |
| if m == nil | |
| m = player.method(name) | |
| end | |
| m.call *args[1..-1] | |
| } | |
| end | |
| end | |
| class MoneyTransfer < Context | |
| @@destinationMethods, @@sourceMethods = nil,nil | |
| def source (*args) | |
| @source.call args | |
| end | |
| def destination (*args) | |
| @destination.call args | |
| end | |
| def initialize(source,destination) | |
| if @@sourceMethods == nil | |
| @@sourceMethods = Hash.new | |
| @@sourceMethods[:withdraw] = lambda{ |amount| | |
| self.source.Movement(amount) | |
| self.source.log "withdrawal #{amount}" | |
| } | |
| end | |
| if @@destinationMethods == nil | |
| @@destinationMethods = Hash.new | |
| @@destinationMethods[:deposit] = lambda{ |amount| | |
| self.destination.Movement(amount) | |
| self.destination.log "deposited #{amount}" | |
| } | |
| end | |
| @source = bind source, @@sourceMethods | |
| @destination = bind destination, @@destinationMethods | |
| end | |
| def transfer(amount) | |
| source:withdraw,-amount | |
| destination:deposit,amount | |
| p (self.source:to_s) | |
| p (self.destination:to_s) | |
| end | |
| end | |
| class Account | |
| def initialize (amount,id) | |
| @balance = amount | |
| @accountid = id | |
| end | |
| def Movement(amount) | |
| @balance+=amount | |
| end | |
| def log(message) | |
| p message | |
| end | |
| def to_s | |
| "balance of #{@accountid}: #{@balance}" | |
| end | |
| end | |
| ctx = MoneyTransfer.new (Account.new 1000, "source"), (Account.new 1000, "destination") | |
| ctx.transfer 100 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment