In Files

  • delegate.rb

Class/Module Index [+]

Quicksearch

Delegator

Delegator is an abstract class used to build delegator pattern objects from subclasses. Subclasses should redefine __getobj__. For a concrete implementation, see SimpleDelegator.

Public Class Methods

new(obj) click to toggle source

Pass in the obj to delegate method calls to. All methods supported by obj will be delegated to.

 
               # File delegate.rb, line 123
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 <<-EOS
        def self.#{method}(*args, &block)
          begin
            __getobj__.__send__(:#{method}, *args, &block)
          rescue Exception
            $@.delete_if{|s| /:in `__getobj__'$/ =~ s} #`
            $@.delete_if{|s| /^\\(eval\\):/ =~ s}
            Kernel::raise
          end
        end
      EOS
    rescue SyntaxError
      raise NameError, "invalid identifier %s" % method, caller(4)
    end
  end
end
            

Public Instance Methods

__getobj__() click to toggle source

This method must be overridden by subclasses and should return the object method calls are being delegated to.

 
               # File delegate.rb, line 176
def __getobj__
  raise NotImplementedError, "need to define `__getobj__'"
end
            
marshal_dump() click to toggle source

Serialization support for the object returned by __getobj__.

 
               # File delegate.rb, line 181
def marshal_dump
  __getobj__
end
            
marshal_load(obj) click to toggle source

Reinitializes delegation from a serialized object.

 
               # File delegate.rb, line 185
def marshal_load(obj)
  initialize_methods(obj)
  __setobj__(obj)
end
            
method_missing(m, *args, &block) click to toggle source

Handles the magic of delegation through __getobj__.

 
               # File delegate.rb, line 155
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
            
respond_to?(m, include_private = false) click to toggle source

Checks for a method provided by this the delegate object by fowarding the call through __getobj__.

 
               # File delegate.rb, line 167
def respond_to?(m, include_private = false)
  return true if super
  return self.__getobj__.respond_to?(m, include_private)
end