| Path: | delegate.rb |
| Last Update: | Thu Nov 11 00:52:08 GMT+10:00 2004 |
Delegation class that delegates even methods defined in super class,
which can not be covered with normal method_missing hack.
Delegator is the abstract delegation class. Need to redefine
`getobj’ method in the subclass. SimpleDelegator is the concrete subclass for simple delegation.
Usage:
foo = Object.new foo2 = SimpleDelegator.new(foo) foo.hash == foo2.hash # => false Foo = DelegateClass(Array) class ExtArray<DelegateClass(Array) ... end
| Delegater | = | Delegator | backward compatibility ^_^;;; | |
| SimpleDelegater | = | SimpleDelegator |
# File delegate.rb, line 95 def DelegateClass(superclass) klass = Class.new methods = superclass.public_instance_methods(true) methods -= ::Kernel.public_instance_methods(false) methods |= ["to_s","to_a","inspect","==","=~","==="] klass.module_eval { def initialize(obj) @_dc_obj = obj end def method_missing(m, *args) unless @_dc_obj.respond_to?(m) super(m, *args) end @_dc_obj.__send__(m, *args) end def __getobj__ @_dc_obj end def __setobj__(obj) @_dc_obj = obj end def clone super __setobj__(__getobj__.clone) end def dup super __setobj__(__getobj__.dup) end } for method in methods begin klass.module_eval "def \#{method}(*args, &block)\nbegin\n@_dc_obj.__send__(:\#{method}, *args, &block)\nrescue\n$@[0,2] = nil\nraise\nend\nend\n" rescue SyntaxError raise NameError, "invalid identifier %s" % method, caller(3) end end return klass end