1 # = delegate -- Support for the Delegation Pattern
3 # Documentation by James Edward Gray II and Gavin Sinclair
7 # This library provides three different ways to delegate method calls to an
8 # object. The easiest to use is SimpleDelegator. Pass an object to the
9 # constructor and all methods supported by the object will be delegated. This
10 # object can be changed later.
12 # Going a step further, the top level DelegateClass method allows you to easily
13 # setup delegation through class inheritance. This is considerably more
14 # flexible and thus probably the most common use for this library.
16 # Finally, if you need full control over the delegation scheme, you can inherit
17 # from the abstract class Delegator and customize as needed. (If you find
18 # yourself needing this control, have a look at _forwardable_, also in the
19 # standard library. It may suit your needs better.)
23 # Be advised, RDoc will not detect delegated methods.
25 # <b>delegate.rb provides full-class delegation via the
26 # DelegateClass() method. For single-method delegation via
27 # def_delegator(), see forwardable.rb.</b>
33 # Here's a simple example that takes advantage of the fact that
34 # SimpleDelegator's delegation object can be changed at any time.
38 # @source = SimpleDelegator.new([])
41 # def stats( records )
42 # @source.__setobj__(records)
44 # "Elements: #{@source.size}\n" +
45 # " Non-Nil: #{@source.compact.size}\n" +
46 # " Unique: #{@source.uniq.size}\n"
51 # puts s.stats(%w{James Edward Gray II})
53 # puts s.stats([1, 2, 3, nil, 4, 5, 1, 2])
67 # Here's a sample of use from <i>tempfile.rb</i>.
69 # A _Tempfile_ object is really just a _File_ object with a few special rules
70 # about storage location and/or when the File should be deleted. That makes for
71 # an almost textbook perfect example of how to use delegation.
73 # class Tempfile < DelegateClass(File)
74 # # constant and class member data initialization...
76 # def initialize(basename, tmpdir=Dir::tmpdir)
77 # # build up file path/name in var tmpname...
79 # @tmpfile = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL, 0600)
85 # # below this point, all methods of File are supported...
93 # SimpleDelegator's implementation serves as a nice example here.
95 # class SimpleDelegator < Delegator
97 # super # pass obj to Delegator constructor, required
98 # @_sd_obj = obj # store obj for future use
102 # @_sd_obj # return object we are delegating to, required
105 # def __setobj__(obj)
106 # @_sd_obj = obj # change delegation object, a feature we're providing
113 # Delegator is an abstract class used to build delegator pattern objects from
114 # subclasses. Subclasses should redefine \_\_getobj\_\_. For a concrete
115 # implementation, see SimpleDelegator.
120 # Pass in the _obj_ to delegate method calls to. All methods supported by
121 # _obj_ will be delegated to.
124 preserved = ::Kernel.public_instance_methods(false)
125 preserved -= ["to_s","to_a","inspect","==","=~","==="]
126 for t in self.class.ancestors
127 preserved |= t.public_instance_methods(false)
128 preserved |= t.private_instance_methods(false)
129 preserved |= t.protected_instance_methods(false)
130 break if t == Delegator
132 preserved << "singleton_method_added"
133 for method in obj.methods
134 next if preserved.include? method
137 def self.#{method}(*args, &block)
138 __getobj__.__send__(:#{method}, *args, &block)
142 raise NameError, "invalid identifier %s" % method, caller(4)
146 alias initialize_methods initialize
148 # Handles the magic of delegation through \_\_getobj\_\_.
149 def method_missing(m, *args)
150 target = self.__getobj__
151 unless target.respond_to?(m)
154 target.__send__(m, *args)
158 # Checks for a method provided by this the delegate object by fowarding the
159 # call through \_\_getobj\_\_.
163 return self.__getobj__.respond_to?(m)
167 # This method must be overridden by subclasses and should return the object
168 # method calls are being delegated to.
171 raise NotImplementedError, "need to define `__getobj__'"
174 # Serialization support for the object returned by \_\_getobj\_\_.
178 # Reinitializes delegation from a serialized object.
179 def marshal_load(obj)
180 initialize_methods(obj)
186 # A concrete implementation of Delegator, this class provides the means to
187 # delegate all supported method calls to the object passed into the constructor
188 # and even to change the object being delegated to at a later time with
191 class SimpleDelegator<Delegator
193 # Pass in the _obj_ you would like to delegate method calls to.
199 # Returns the current object method calls are being delegated to.
205 # Changes the delegate object to _obj_.
207 # It's important to note that this does *not* cause SimpleDelegator's methods
208 # to change. Because of this, you probably only want to change delegation
209 # to objects of the same type as the original delegate.
211 # Here's an example of changing the delegation object.
213 # names = SimpleDelegator.new(%w{James Edward Gray II})
214 # puts names[1] # => Edward
215 # names.__setobj__(%w{Gavin Sinclair})
216 # puts names[1] # => Sinclair
219 raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
223 # Clone support for the object returned by \_\_getobj\_\_.
226 __setobj__(__getobj__.clone)
228 # Duplication support for the object returned by \_\_getobj\_\_.
231 __setobj__(__getobj__.dup)
236 # backward compatibility ^_^;;;
237 Delegater = Delegator
238 SimpleDelegater = SimpleDelegator
242 # The primary interface to this library. Use to setup delegation when defining
245 # class MyClass < DelegateClass( ClassToDelegateTo ) # Step 1
247 # super(obj_of_ClassToDelegateTo) # Step 2
251 def DelegateClass(superclass)
253 methods = superclass.public_instance_methods(true)
254 methods -= ::Kernel.public_instance_methods(false)
262 methods |= ["to_s","to_a","inspect","==","=~","==="]
265 def initialize(obj) # :nodoc:
269 def method_missing(m, *args) # :nodoc:
270 unless @_dc_obj.respond_to?(m)
273 @_dc_obj.__send__(m, *args)
276 def respond_to?(m) # :nodoc:
278 return @_dc_obj.respond_to?(m)
281 def __getobj__ # :nodoc:
285 def __setobj__(obj) # :nodoc:
286 raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
292 __setobj__(__getobj__.clone)
297 __setobj__(__getobj__.dup)
301 methods.each do |method|
303 klass.module_eval <<-EOS
304 def #{method}(*args, &block)
305 @_dc_obj.__send__(:#{method}, *args, &block)
309 raise NameError, "invalid identifier #{method}"
318 class ExtArray<DelegateClass(Array)
336 foo2 = SimpleDelegator.new(foo)
337 p foo.test == foo2.test # => true
338 foo2.error # raise error!