-
Notifications
You must be signed in to change notification settings - Fork 105
/
proxy.rb
64 lines (52 loc) · 1.05 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
54
55
56
57
58
59
60
61
62
63
64
require 'forwardable'
# Provide a surrogate or placeholder for another object to control
# access to it
class Hero
attr_accessor :keywords
def initialize
@keywords = []
end
end
class ComputerProxy
# Forwardable allows objects to run methods on behalf
# of it's members, in this case the Computer object
extend Forwardable
# We delegate the ComputerProxy's use of
# the Computer object's add method
def_delegators :real_object, :add
def initialize(hero)
@hero = hero
end
def execute
check_access
real_object.execute
end
def check_access
unless @hero.keywords.include?(:computer)
raise "You have no access"
end
end
def real_object
@real_object ||= Computer.new
end
end
class Computer
def initialize
@queue = []
end
def add(command)
@queue << command
end
def execute
"executing commands"
end
end
# Usage
hero = Hero.new
proxy = ComputerProxy.new(hero)
proxy.add("some command")
proxy.execute
# => raise error
hero.keywords << :computer
proxy.execute
# => executing commands