Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Created March 25, 2013 00:13
Show Gist options
  • Save ackintosh/5234171 to your computer and use it in GitHub Desktop.
Save ackintosh/5234171 to your computer and use it in GitHub Desktop.
Proxy pattern in Ruby
# -*- encoding: utf-8 -*-
class VirtualAccountProxy
def initialize(&creation_block)
@creation_block = creation_block
end
def deposit(amount)
s = subject
return s.deposit(amount)
end
def withdraw(amount)
s = subject
return s.withdraw(amount)
end
def balance
s = subject
return s.balance
end
def subject
@subject || (@subject = @creation_block.call)
end
end
class BankAccount
def initialize(starting_balance)
@balance = starting_balance
end
def method_missing(method_name, *args)
p method_name
p args
end
end
proxy = VirtualAccountProxy.new do
BankAccount.new(10)
end
proxy.withdraw(5)
# :withdraw
# [5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment