In: |
delegate.rb
|
Parent: | Object |
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
initialize | -> | initialize_methods |
# File delegate.rb, line 21 def initialize(obj) preserved = ::Kernel.public_instance_methods(false) preserved -= ["to_s","to_a","inspect","==","=~","==="] for t in self.class.ancestors preserved |= t.public_instance_methods(false) preserved |= t.private_instance_methods(false) preserved |= t.protected_instance_methods(false) break if t == Delegator end preserved << "singleton_method_added" for method in obj.methods next if preserved.include? method begin eval "def self.\#{method}(*args, &block)\nbegin\n__getobj__.__send__(:\#{method}, *args, &block)\nrescue Exception\n$@.delete_if{|s| /:in `__getobj__'$/ =~ s} \#`\n$@.delete_if{|s| /^\\\\(eval\\\\):/ =~ s}\nKernel::raise\nend\nend\n" rescue SyntaxError raise NameError, "invalid identifier %s" % method, caller(4) end end end
# File delegate.rb, line 53 def __getobj__ raise NotImplementedError, "need to define `__getobj__'" end