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 # @delegate_sd_obj = obj # store obj for future use
102 # @delegate_sd_obj # return object we are delegating to, required
105 # def __setobj__(obj)
106 # @delegate_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.
119 :__id__, :object_id, :__send__, :public_send, :respond_to?, :send,
120 :instance_eval, :instance_exec, :extend,
122 instance_methods.each do |m|
123 next if preserved.include?(m)
127 module MethodDelegation
129 # Pass in the _obj_ to delegate method calls to. All methods supported by
130 # _obj_ will be delegated to.
136 # Handles the magic of delegation through \_\_getobj\_\_.
137 def method_missing(m, *args, &block)
139 target = self.__getobj__
140 unless target.respond_to?(m)
141 super(m, *args, &block)
143 target.__send__(m, *args, &block)
146 $@.delete_if{|s| %r"\A#{__FILE__}:\d+:in `method_missing'\z"o =~ s}
152 # Checks for a method provided by this the delegate object by fowarding the
153 # call through \_\_getobj\_\_.
155 def respond_to?(m, include_private = false)
157 return self.__getobj__.respond_to?(m, include_private)
161 # Returns true if two objects are considered same.
164 return true if obj.equal?(self)
165 self.__getobj__ == obj
169 # Returns true only if two objects are identical.
172 self.object_id == obj.object_id
176 # This method must be overridden by subclasses and should return the object
177 # method calls are being delegated to.
180 raise NotImplementedError, "need to define `__getobj__'"
184 # This method must be overridden by subclasses and change the object delegate
188 raise NotImplementedError, "need to define `__setobj__'"
191 # Serialization support for the object returned by \_\_getobj\_\_.
195 # Reinitializes delegation from a serialized object.
196 def marshal_load(obj)
200 # Clone support for the object returned by \_\_getobj\_\_.
203 new.__setobj__(__getobj__.clone)
206 # Duplication support for the object returned by \_\_getobj\_\_.
209 new.__setobj__(__getobj__.dup)
213 include MethodDelegation
217 # A concrete implementation of Delegator, this class provides the means to
218 # delegate all supported method calls to the object passed into the constructor
219 # and even to change the object being delegated to at a later time with
222 class SimpleDelegator<Delegator
223 # Returns the current object method calls are being delegated to.
229 # Changes the delegate object to _obj_.
231 # It's important to note that this does *not* cause SimpleDelegator's methods
232 # to change. Because of this, you probably only want to change delegation
233 # to objects of the same type as the original delegate.
235 # Here's an example of changing the delegation object.
237 # names = SimpleDelegator.new(%w{James Edward Gray II})
238 # puts names[1] # => Edward
239 # names.__setobj__(%w{Gavin Sinclair})
240 # puts names[1] # => Sinclair
243 raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
244 @delegate_sd_obj = obj
249 def Delegator.delegating_block(mid)
250 lambda do |*args, &block|
252 @delegate_dc_obj.__send__(mid, *args, &block)
254 re = /\A#{Regexp.quote(__FILE__)}:#{__LINE__-2}:/o
255 $!.backtrace.delete_if {|t| re =~ t}
263 # The primary interface to this library. Use to setup delegation when defining
266 # class MyClass < DelegateClass( ClassToDelegateTo ) # Step 1
268 # super(obj_of_ClassToDelegateTo) # Step 2
272 def DelegateClass(superclass)
274 methods = superclass.public_instance_methods(true)
276 :__id__, :object_id, :__send__, :public_send, :respond_to?, :send,
277 :==, :equal?, :initialize, :method_missing, :__getobj__, :__setobj__,
278 :clone, :dup, :marshal_dump, :marshal_load, :instance_eval, :instance_exec,
282 include Delegator::MethodDelegation
283 def __getobj__ # :nodoc:
286 def __setobj__(obj) # :nodoc:
287 raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
288 @delegate_dc_obj = obj
292 methods.each do |method|
293 define_method(method, Delegator.delegating_block(method))
302 class ExtArray<DelegateClass(Array)
325 foo2 = SimpleDelegator.new(foo)
327 foo2.instance_eval{print "foo\n"}
328 p foo.test == foo2.test # => true
329 p foo2.iter{[55,true]} # => true
330 foo2.error # raise error!