Created
April 28, 2014 19:20
-
-
Save cheeyeo/11381532 to your computer and use it in GitHub Desktop.
Simple decorator pattern
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 AuditLog | |
| def record(number, action, amount, balance) | |
| printf( | |
| "%<time>s #%<number>s %<action>s %<amount>.2f (%<balance>.2f)\n", | |
| time: Time.now, | |
| number: number, | |
| action: action, | |
| amount: amount / 100, | |
| balance: balance / 100) | |
| end | |
| end |
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
| require 'delegate' | |
| class AuditedAccount < SimpleDelegator | |
| def initialize(account, audit_log) | |
| super(account) | |
| @audit_log = audit_log | |
| end | |
| def deposit(amount) | |
| super | |
| @audit_log.record(number, :deposit, amount, balance_cents) | |
| end | |
| def withdraw(amount) | |
| super | |
| @audit_log.record(number, :withdraw, amount, balance_cents) | |
| end | |
| end |
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 BankAccount | |
| def initialize(number) | |
| @number = number | |
| @balance_cents = 0 | |
| end | |
| def deposit(amount) | |
| @balance_cents += amount | |
| end | |
| def withdraw(amount) | |
| @balance_cents -= amount | |
| end | |
| def inspect | |
| "#<%s %s ($%0.2f)>" % | |
| [self.class, @number, @balance_cents / 100.0] | |
| end | |
| alias_method :to_s, :inspect | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment