-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathghost_methods.rb
More file actions
47 lines (42 loc) · 962 Bytes
/
ghost_methods.rb
File metadata and controls
47 lines (42 loc) · 962 Bytes
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
class MyClass
def a_real_method
"100% alberta beef"
end
def method_missing(name, *args)
if name == :ghost_method
return "Spooky!"
end
super
end
end
# obj = MyClass.new
# p obj.a_real_method
# #=> "100% alberta beef"
# p obj.ghost_method
# #=> "Spooky!"
# p obj.respond_to?(:a_real_method)
# #=> true
# p obj.respond_to?(:ghost_method)
# #=> false
# p obj.public_methods(false)
# #=> [:method_missing, :a_real_method]
# # p obj.method(:ghost_method)
# #=> undefined method `ghost_method'
class MyClass
def respond_to_missing?(name, *args)
!!(name == :ghost_method || super(name, *args))
end
end
obj = MyClass.new
p obj.a_real_method
#=> "100% alberta beef"
p obj.ghost_method
#=> "Spooky!"
p obj.public_methods(false)
#=> [:respond_to?, :method_missing, :a_real_method]
p obj.respond_to?(:a_real_method)
#=> true
p obj.respond_to?(:ghost_method)
#=> true
p obj.method(:ghost_method)
#=> #<Method: MyClass#ghost_method>