作为一个编程练习,我编写了一个Ruby片段来创建一个类,实例化两个来自该类的对象,monkeypatch(猴子补丁)其中一个对象,并依赖于method_missing来monkeypatch另一个对象。
以下是关键点。这可以按预期工作:
以下是关键点。这可以按预期工作:
class Monkey
def chatter
puts "I am a chattering monkey!"
end
def method_missing(m)
puts "No #{m}, so I'll make one..."
def screech
puts "This is the new screech."
end
end
end
m1 = Monkey.new
m2 = Monkey.new
m1.chatter
m2.chatter
def m1.screech
puts "Aaaaaargh!"
end
m1.screech
m2.screech
m2.screech
m1.screech
m2.screech
你会注意到我有一个method_missing参数。我这样做是因为我希望使用define_method动态创建缺失的方法并赋予适当的名称。但是它不起作用。事实上,即使像这样使用具有静态名称的define_method:
def method_missing(m)
puts "No #{m}, so I'll make one..."
define_method(:screech) do
puts "This is the new screech."
end
end
最终结果如下:
ArgumentError: wrong number of arguments (2 for 1)
method method_missing in untitled document at line 9
method method_missing in untitled document at line 9
at top level in untitled document at line 26
Program exited.
错误提示更让人困惑的是,我只为method_missing
提供了一个参数...
method_missing
中使用白名单,以便仅处理您实际感兴趣的那些方法,并且将您不想处理的所有内容使用super
“上移”,向上转发。 - Jörg W Mittag