我有几个扩展方法缺失的模块:
module SaysHello
def respond_to?(method)
super.respond_to?(method) || !!(method.to_s =~ /^hello/)
end
def method_missing(method, *args, &block)
if (method.to_s =~ /^hello/)
puts "Hello, #{method}"
else
super.method_missing(method, *args, &block)
end
end
end
module SaysGoodbye
def respond_to?(method)
super.respond_to?(method) || !!(method.to_s =~ /^goodbye/)
end
def method_missing(method, *args, &block)
if (method.to_s =~ /^goodbye/)
puts "Goodbye, #{method}"
else
super.method_missing(method, *args, &block)
end
end
end
class ObjectA
include SaysHello
end
class ObjectB
include SaysGoodbye
end
这一切都很好,例如ObjectA.new.hello_there输出"Hello, hello_there"。同样,ObjectB.new.goodbye_xxx输出"Goodbye, xxx". respond_to?也可以,例如ObjectA.new.respond_to? :hello_there返回 true。
SaysHello但是,当您想同时使用and时,这并不能很好地工作SaysGoodbye:
class ObjectC
include SaysHello
include SaysGoodbye
end
虽然ObjectC.new.goodbye_aaa工作正常,但ObjectC.new.hello_a行为奇怪:
> ObjectC.new.hello_aaa
Hello, hello_aaa
NoMethodError: private method `method_missing' called for nil:NilClass
from test.rb:22:in `method_missing' (line 22 was the super.method_missing line in the SaysGoodbye module)
它正确输出,然后引发错误。也不respond_to?正确,ObjectC.new.respond_to? :hello_a返回false。
最后,添加这个类:
class ObjectD
include SaysHello
include SaysGoodbye
def respond_to?(method)
super.respond_to?(method) || !!(method.to_s =~ /^lol/)
end
def method_missing(method, *args, &block)
if (method.to_s =~ /^lol/)
puts "Haha, #{method}"
else
super.method_missing(method, *args, &block)
end
end
end
行为也很奇怪。ObjectD.new.lol_zzz有效,但是 ObjectD.new.hello_aand ObjectD.new.goodbye_t在输出正确的字符串后都会抛出一个名称异常。respond_to?hello 和 goodbye 方法也失败了。
有没有办法让这一切正常工作?解释如何method_missing、模块和super交互也是非常有用的。
编辑:coreyward 解决了这个问题,如果我super.<method-name>(args...)在我定义的所有方法中使用 super 而不是,程序可以正常工作。我不明白为什么会这样,所以我在Super.<method-name> 在 ruby 中做了什么?