我想做一些涉及挂钩GC.start调用的实验。
有了这个,ruby告诉我GC不是一个类:
class GC
def self.start
puts "hello"
super
end
end
由此,ruby告诉我GC.start没有超类(因此,我认为我实际上并没有加入原始类,而是以某种方式接管了该名称)。
module GC
def self.start
puts "hello"
super
end
end
GC.start
我如何monkeypatch GC.start?
让我们重新定义GC::start
,以便我们可以看到它何时被调用。
module GC
def self.start
"start redefined"
end
end
一种方法如下:
module GC
class << self
alias old_start start
end
def self.start
"new start"
old_start
end
end
GC.start
#=> "new start"
#=> "start redefined"
另一个是:
module X
def self.start
"new start"
super_method.call
end
end
module GC
class << self
prepend X
end
end
GC.start
#=> "new start"
#=> "start redefined"