2010-09-02 67 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