Skip to content

Instantly share code, notes, and snippets.

@cheeyeo
Created April 28, 2014 19:20
Show Gist options
  • Save cheeyeo/11381532 to your computer and use it in GitHub Desktop.
Save cheeyeo/11381532 to your computer and use it in GitHub Desktop.
Simple decorator pattern
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
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
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