Created
          March 25, 2013 00:13 
        
      - 
      
- 
        Save ackintosh/5234171 to your computer and use it in GitHub Desktop. 
    Proxy pattern in Ruby
  
        
  
    
      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
    
  
  
    
  | # -*- 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