-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.rb
53 lines (52 loc) · 1.15 KB
/
proxy.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class BankAccount
attr_reader :balance
def initialize(starting_balance = 0)
@balance = starting_balance
end
def deposit(amount)
@balance += amount
end
def withdraw(amount)
@balance -= amount
end
end
class VirtualAccountProxy
def initialize(starting_balance=0)
@starting_balance = starting_balance
end
def subject
@subject || (@subject = BankAccount.new(100))
end
def deposit(amount)
s = subject
s.deposit(amount)
end
def withdraw(amount)
s = subject
s.withdraw(amount)
end
def balance
s = subject
s.balance
end
end
puts "Hard coded BankAccount into VirtualAccountProxy"
v = VirtualAccountProxy.new {BankAccount.new(100)}
puts v.balance
#Eliminating that proxy drudgery or code duplication, using method_missing
class VitualProxy
def initialize(&creation_block)
@creation_block = creation_block
end
def method_missing(name, *args)
s = subject
s.send(name, *args)
end
def subject
@subject || (@subject = @creation_block.call)
end
end
puts "Using method_missing and object creation block"
v1 = VitualProxy.new {BankAccount.new(9000)}
puts v1.balance
puts v1.deposit(21000)