Delegator is an abstract class used to build delegator pattern objects from subclasses. Subclasses should redefine __getobj__. For a concrete implementation, see SimpleDelegator.
Pass in the obj to delegate method calls to. All methods supported by obj will be delegated to.
# File delegate.rb, line 124
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)
begin
__getobj__.__send__(:#{method}, *args, &block)
ensure
$@.delete_if{|s|IgnoreBacktracePat=~s} if $@
end
end
", nil, __FILE__, __LINE__+1
rescue SyntaxError
raise NameError, "invalid identifier %s" % method, caller(4)
end
end
end
This method must be overridden by subclasses and should return the object method calls are being delegated to.
# File delegate.rb, line 175
def __getobj__
raise NotImplementedError, "need to define `__getobj__'"
end
Serialization support for the object returned by __getobj__.
# File delegate.rb, line 180
def marshal_dump
__getobj__
end
Reinitializes delegation from a serialized object.
# File delegate.rb, line 184
def marshal_load(obj)
initialize_methods(obj)
__setobj__(obj)
end
Handles the magic of delegation through __getobj__.
# File delegate.rb, line 154
def method_missing(m, *args, &block)
target = self.__getobj__
unless target.respond_to?(m)
super(m, *args, &block)
end
target.__send__(m, *args, &block)
end
Checks for a method provided by this the delegate object by fowarding the call through __getobj__.
# File delegate.rb, line 166
def respond_to?(m, include_private = false)
return true if super
return self.__getobj__.respond_to?(m, include_private)
end
Commenting is here to help enhance the documentation. For example, code samples, or clarification of the documentation.
If you have questions about Ruby or the documentation, please post to one of the Ruby mailing lists. You will get better, faster, help that way.
If you wish to post a correction of the docs, please do so, but also file bug report so that it can be corrected for the next release. Thank you.
If you want to help improve the Ruby documentation, please see Improve the docs, or visit Documenting-ruby.org.