2010-09-02 63 views
0
p parent.class #=> NilClass # ok. 
p !!parent # => false # as expected. 
p parent.object_id # => 17006820 # should be 4 
p parent && parent.foo # => NoMethodError foo # should be nil-guarded 

此对象从哪里来?这里发生了什么? (无红宝石)

+0

sepp2k可以做出很好的假设,但现在,这里没有真正的问题。 – theIV 2010-09-02 15:59:06

回答

2

可能是这样的:

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 

创建BlankSlateBasicObject是一种常见的模式(它被添加到核心红宝石为1.9之前的版本)。它用于创建对象,使用它们发送的任何方法做一些特殊的事情,或者将他们的行为严重委托给不同的类。缺点是它可能会引入这样的奇怪行为。

+0

不错的。 (rdb:1)p Object.instance_method(:class).bind(parent).call YARD :: StubProxy – Reactormonk 2010-09-02 16:36:23