可能是这样的:
class BlankSlate
instance_methods.each do |m|
# Undefine all but a few methods. Various implementations leave different
# methods behind.
undef_method(m) unless m.to_s == "object_id"
end
end
class Foo < BlankSlate
def method_missing(*args)
delegate.send(*args)
end
def delegate
# This probably contains an error and returns nil accidentally.
nil
end
end
parent = Foo.new
p parent.class
#=> NilClass
p !!parent
#=> false
p parent.object_id
#=> 2157246780
p parent && parent.foo
#=> NoMethodError: undefined method `foo' for nil:NilClass
创建BlankSlate
或BasicObject
是一种常见的模式(它被添加到核心红宝石为1.9之前的版本)。它用于创建对象,使用它们发送的任何方法做一些特殊的事情,或者将他们的行为严重委托给不同的类。缺点是它可能会引入这样的奇怪行为。
sepp2k可以做出很好的假设,但现在,这里没有真正的问题。 – theIV 2010-09-02 15:59:06