Guest User

Untitled

a guest
Oct 15th, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. class Account
  2. attr_reader :account_id, :balance
  3.  
  4. def initialize(account_id)
  5. @account_id = account_id
  6. @balance = 0
  7. end
  8.  
  9. def withdraw(amount)
  10. raise "Insufficient funds" if amount < 0
  11. @balance -= amount
  12. end
  13.  
  14. def deposit(amount)
  15. @balance += amount
  16. end
  17.  
  18. def update_log(msg, date, amount)
  19. puts "Account: #{inspect}, #{msg}, #{date.to_s}, #{amount}"
  20. end
  21.  
  22. def self.find(account_id)
  23. @@store ||= Hash.new
  24. return @@store[account_id] if @@store.has_key? account_id
  25.  
  26. if :savings == account_id
  27. account = SavingsAccount.new(account_id)
  28. account.deposit(100000)
  29. elsif :checking == account_id
  30. account = CheckingAccount.new(account_id)
  31. else
  32. account = Account.new(account_id)
  33. end
  34. @@store[account_id] = account
  35. account
  36. end
  37. end
  38.  
  39. module MoneySource
  40. include Rdci::Role
  41.  
  42. def transfer_out
  43. raise "Insufficient funds" if balance < Amount
  44. withdraw Amount
  45. DestinationAccount.deposit Amount
  46. update_log "Transfer Out", Time.now, Amount
  47. DestinationAccount.update_log "Transfer In", Time.now, Amount
  48. end
  49.  
  50. end
  51.  
  52. class TransferMoneyContext
  53. include Rdci::Context
  54.  
  55. attr_reader :source_account, :destination_account, :amount
  56.  
  57. def self.execute(amt, source_account_id, destination_account_id)
  58. TransferMoneyContext.new(amt, source_account_id, destination_account_id).execute
  59. end
  60.  
  61. def initialize(amt, source_account_id, destination_account_id)
  62. @source_account = Account.find(source_account_id)
  63. @source_account.mixin MoneySource
  64.  
  65. @destination_account = Account.find(destination_account_id)
  66. @amount = amt
  67. end
  68.  
  69. def execute
  70. in_context do
  71. source_account.transfer_out
  72. end
  73. @source_account.unmix MoneySource
  74. end
  75.  
  76. end
  77.  
  78. class SavingsAccount < Account
  79. end
  80.  
  81. class CheckingAccount < Account
  82. end
  83.  
  84. TransferMoneyContext.execute(300, :savings, :checking)
  85.  
  86. puts "Savings: #{Account.find(:savings).balance}, Checking: #{Account.find(:checking).balance}"
Add Comment
Please, Sign In to add comment