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)
139
__getobj__.__send__(:#{method}, *args, &block)
141
$@.delete_if{|s| /:in `__getobj__'$/ =~ s} #`
142
$@.delete_if{|s| /^\\(eval\\):/ =~ s}
148
raise NameError, "invalid identifier %s" % method, caller(4)
152
alias initialize_methods initialize
154
# Handles the magic of delegation through \_\_getobj\_\_.
155
def method_missing(m, *args)
156
target = self.__getobj__
157
unless target.respond_to?(m)
160
target.__send__(m, *args)
164
# Checks for a method provided by this the delegate object by fowarding the
165
# call through \_\_getobj\_\_.
169
return self.__getobj__.respond_to?(m)
173
# This method must be overridden by subclasses and should return the object
174
# method calls are being delegated to.
177
raise NotImplementedError, "need to define `__getobj__'"
180
# Serialization support for the object returned by \_\_getobj\_\_.
184
# Reinitializes delegation from a serialized object.
185
def marshal_load(obj)
186
initialize_methods(obj)
192
# A concrete implementation of Delegator, this class provides the means to
193
# delegate all supported method calls to the object passed into the constructor
194
# and even to change the object being delegated to at a later time with
197
class SimpleDelegator<Delegator
199
# Pass in the _obj_ you would like to delegate method calls to.
205
# Returns the current object method calls are being delegated to.
211
# Changes the delegate object to _obj_.
213
# It's important to note that this does *not* cause SimpleDelegator's methods
214
# to change. Because of this, you probably only want to change delegation
215
# to objects of the same type as the original delegate.
217
# Here's an example of changing the delegation object.
219
# names = SimpleDelegator.new(%w{James Edward Gray II})
220
# puts names[1] # => Edward
221
# names.__setobj__(%w{Gavin Sinclair})
222
# puts names[1] # => Sinclair
225
raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
229
# Clone support for the object returned by \_\_getobj\_\_.
232
__setobj__(__getobj__.clone)
234
# Duplication support for the object returned by \_\_getobj\_\_.
237
__setobj__(__getobj__.dup)
242
# backward compatibility ^_^;;;
243
Delegater = Delegator
244
SimpleDelegater = SimpleDelegator
248
# The primary interface to this library. Use to setup delegation when defining
251
# class MyClass < DelegateClass( ClassToDelegateTo ) # Step 1
253
# super(obj_of_ClassToDelegateTo) # Step 2
257
def DelegateClass(superclass)
259
methods = superclass.public_instance_methods(true)
260
methods -= ::Kernel.public_instance_methods(false)
261
methods |= ["to_s","to_a","inspect","==","=~","==="]
263
def initialize(obj) # :nodoc:
266
def method_missing(m, *args) # :nodoc:
267
unless @_dc_obj.respond_to?(m)
270
@_dc_obj.__send__(m, *args)
272
def respond_to?(m) # :nodoc:
274
return @_dc_obj.respond_to?(m)
276
def __getobj__ # :nodoc:
279
def __setobj__(obj) # :nodoc:
280
raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
285
__setobj__(__getobj__.clone)
289
__setobj__(__getobj__.dup)
292
for method in methods
294
klass.module_eval <<-EOS
295
def #{method}(*args, &block)
297
@_dc_obj.__send__(:#{method}, *args, &block)
305
raise NameError, "invalid identifier %s" % method, caller(3)
314
class ExtArray<DelegateClass(Array)
332
foo2 = SimpleDelegator.new(foo)
333
p foo.test == foo2.test # => true
334
foo2.error # raise error!