我有一个疱疹的时刻。我可以发誓这行得通:
module StubbedGreeting
def sayit
puts "StubbedGreeting"
end
end
module RegularGreeting
def sayit
puts "RegularGreeting"
end
end
class Greeting
def sayit
raise "Gotta catch me!"
end
end
class GreetingIncludes
include RegularGreeting
end
begin
Greeting.send(:include, StubbedGreeting)
Greeting.new.sayit
rescue Exception
puts "Exception raised"
end
GreetingIncludes.send(:include, StubbedGreeting)
GreetingIncludes.new.sayit
这里发生的Greeting.new.sayit
结果rescue
是调用块,忽略 StubbedGreeting 尝试的覆盖。
但是,GreetingIncludes.new.sayit
结果是“StubbedGreeting”,也不例外。
所以一个模块可以覆盖另一个模块的方法,但不能覆盖已经直接在类中定义的方法?
我知道如何解决这个问题,我只是觉得很奇怪。