In Files

  • delegate.rb

Parent

Methods

Class/Module Index [+]

Quicksearch

Object

Public Instance Methods

DelegateClass(superclass) click to toggle source

The primary interface to this library. Use to setup delegation when defining your class.

class MyClass < DelegateClass( ClassToDelegateTo )    # Step 1
  def initiaize
    super(obj_of_ClassToDelegateTo)                   # Step 2
  end
end
 
               # File delegate.rb, line 259
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)  # :nodoc:
      @_dc_obj = obj
    end
    def method_missing(m, *args)  # :nodoc:
      unless @_dc_obj.respond_to?(m)
        super(m, *args)
      end
      @_dc_obj.__send__(m, *args)
    end
    def respond_to?(m, include_private = false)  # :nodoc:
      return true if super
      return @_dc_obj.respond_to?(m, include_private)
    end
    def __getobj__  # :nodoc:
      @_dc_obj
    end
    def __setobj__(obj)  # :nodoc:
      raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
      @_dc_obj = obj
    end
    def clone  # :nodoc:
      new = super
      new.__setobj__(__getobj__.clone)
      new
    end
    def dup  # :nodoc:
      new = super
      new.__setobj__(__getobj__.clone)
      new
    end
  }
  for method in methods
    begin
      klass.module_eval <<-EOS
        def #{method}(*args, &block)
          begin
            @_dc_obj.__send__(:#{method}, *args, &block)
          rescue
            $@[0,2] = nil
            raise
          end
        end
      EOS
    rescue SyntaxError
      raise NameError, "invalid identifier %s" % method, caller(3)
    end
  end
  return klass
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 visit Documenting-ruby.org.

blog comments powered by Disqus