A trap of delegation
April 6th 2011Beware of proxy objects. Here is an edge case I fell into and want to warn you.
Let’s consider an ultimate proxy class:
It delegates virtually everything to a given object. And one would think (yeahl, including me) that we can use this proxy object everywhere instead of the genuine object.
Counterexample
That’s not true and here is the trap:
A genuine object will pass this check:
But proxy object will not:
Why?
Because case internally uses #=== to determine if a given object
belongs to a certain “when-block”. Look:
It’s easier to track down in Rubinius:
Object::kind_of_p at vm/builtin/object.cpp:428
Module::case_compare at vm/builtin/module.cpp:66
…
Module#=== at kernel/common/module.rb:572
You see? Not a single chance to have an influence on this process from a Ruby level.