-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmethod_missing_actions_hash.rb
More file actions
69 lines (60 loc) · 1.2 KB
/
Copy pathmethod_missing_actions_hash.rb
File metadata and controls
69 lines (60 loc) · 1.2 KB
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
65
66
67
68
69
MSGS =
{
:dance => 'is dancing',
:poo => 'is a smelly doggy!',
:laugh => 'finds this hilarious!'
}
class Dog
attr_accessor :actions, :name
def initialize(name)
@name = name
@actions = {}
end
def can(*actions, &block)
actions.each do |a|
unless @actions.include?(a)
if block.nil?
@actions[a] = "#{@name} #{MSGS[a]}"
else
@actions[a] = instance_eval &block
end
end
end
end
def method_missing(name, *args, &block)
if @actions.include?(name)
@actions[name]
else
"#{@name} doesn't understand #{name}"
end
end
end
lassie, fido, stimpy = %w[Lassie Fido Stimpy].collect{|name| Dog.new(name)}
lassie.can :dance, :poo, :laugh
fido.can(:poo){ "#{name} is smelly." }
stimpy.can :dance
stimpy.can(:cry){ "#{name} cried AHHHH" }
p lassie.dance
p lassie.poo
p lassie.laugh
puts
p fido.dance
p fido.poo
p fido.laugh
puts
p stimpy.dance
p stimpy.poo
p stimpy.laugh
p stimpy.cry
=begin OUTPUT
"Lassie is dancing"
"Lassie is a smelly doggy!"
"Lassie finds this hilarious!"
"Fido doesn't understand dance"
"Fido is smelly."
"Fido doesn't understand laugh"
"Stimpy is dancing"
"Stimpy doesn't understand poo"
"Stimpy doesn't understand laugh"
"Stimpy cried AHHHH"
=end