-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.rb
executable file
·64 lines (55 loc) · 1.26 KB
/
example.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
#!/usr/bin/env ruby
$: << "."
require "cop/context"
class House
def entering(visitor)
visitor.context.activate
end
def leaving(visitor)
visitor.context.deactivate
end
def play_song
"the hall of the mountain king (by default)"
end
end
class Visitor
attr_reader :context
def initialize(name, song)
@name = name
@song = song
@context = Context.named(name)
@context.adapt_class(House, :play_song, lambda { |*args| "#{@song} (for #{self.to_s})" })
end
def to_s
@name
end
end
house = House.new
alice = Visitor.new("alice", "the imperial march")
john = Visitor.new("john", "nutcracker theme")
puts house.play_song
house.entering(alice)
puts house.play_song
house.entering(john)
puts house.play_song
house.leaving(john)
puts house.play_song
house.leaving(alice)
puts house.play_song
class HearingImpaired < Visitor
def initialize(name)
@name = name
@context = Context.named(name)
@context.adapt_class(House, :play_song, lambda { |*args| "#{Context.proceed} LOUDLY (for #{self.to_s})" })
end
end
stan = HearingImpaired.new("stan")
puts house.play_song
house.entering(alice)
puts house.play_song
house.entering(stan)
puts house.play_song
house.leaving(stan)
puts house.play_song
house.leaving(alice)
puts house.play_song