1 # frozen_string_literal: true
2 # = delegate -- Support for the Delegation Pattern
4 # 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 which is also in
19 # the standard library. It may suit your needs better.)
21 # SimpleDelegator's implementation serves as a nice example of the use of
26 # class SimpleDelegator < Delegator
28 # @delegate_sd_obj # return object we are delegating to, required
32 # @delegate_sd_obj = obj # change delegation object,
33 # # a feature we're providing
39 # Be advised, RDoc will not detect delegated methods.
41 class Delegator < BasicObject
47 [:to_s, :inspect, :!~, :===, :<=>, :hash].each do |m|
50 private_instance_methods.each do |m|
51 if /\Ablock_given\?\z|\Aiterator\?\z|\A__.*__\z/ =~ m
60 def self.const_missing(n)
67 # Use #__raise__ if your Delegator does not have a object to delegate the
72 # Pass in the _obj_ to delegate method calls to. All methods supported by
73 # _obj_ will be delegated to.
80 # Handles the magic of delegation through \_\_getobj\_\_.
82 ruby2_keywords def method_missing(m, *args, &block)
84 target = self.__getobj__ {r = false}
86 if r && target_respond_to?(target, m, false)
87 target.__send__(m, *args, &block)
88 elsif ::Kernel.method_defined?(m) || ::Kernel.private_method_defined?(m)
89 ::Kernel.instance_method(m).bind_call(self, *args, &block)
91 super(m, *args, &block)
96 # Checks for a method provided by this the delegate object by forwarding the
97 # call through \_\_getobj\_\_.
99 def respond_to_missing?(m, include_private)
101 target = self.__getobj__ {r = false}
102 r &&= target_respond_to?(target, m, include_private)
103 if r && include_private && !target_respond_to?(target, m, false)
104 warn "delegator does not forward private method \##{m}", uplevel: 3
110 KERNEL_RESPOND_TO = ::Kernel.instance_method(:respond_to?)
111 private_constant :KERNEL_RESPOND_TO
113 # Handle BasicObject instances
114 private def target_respond_to?(target, m, include_private)
117 target.respond_to?(m, include_private)
119 if KERNEL_RESPOND_TO.bind_call(target, :respond_to?)
120 target.respond_to?(m, include_private)
122 KERNEL_RESPOND_TO.bind_call(target, m, include_private)
128 # Returns the methods available to this delegate object as the union
129 # of this object's and \_\_getobj\_\_ methods.
131 def methods(all=true)
132 __getobj__.methods(all) | super
136 # Returns the methods available to this delegate object as the union
137 # of this object's and \_\_getobj\_\_ public methods.
139 def public_methods(all=true)
140 __getobj__.public_methods(all) | super
144 # Returns the methods available to this delegate object as the union
145 # of this object's and \_\_getobj\_\_ protected methods.
147 def protected_methods(all=true)
148 __getobj__.protected_methods(all) | super
151 # Note: no need to specialize private_methods, since they are not forwarded
154 # Returns true if two objects are considered of equal value.
157 return true if obj.equal?(self)
158 self.__getobj__ == obj
162 # Returns true if two objects are not considered of equal value.
165 return false if obj.equal?(self)
170 # Returns true if two objects are considered of equal value.
173 return true if obj.equal?(self)
178 # Delegates ! to the \_\_getobj\_\_
185 # This method must be overridden by subclasses and should return the object
186 # method calls are being delegated to.
189 __raise__ ::NotImplementedError, "need to define '__getobj__'"
193 # This method must be overridden by subclasses and change the object delegate
197 __raise__ ::NotImplementedError, "need to define '__setobj__'"
201 # Serialization support for the object returned by \_\_getobj\_\_.
204 ivars = instance_variables.reject {|var| /\A@delegate_/ =~ var}
207 ivars, ivars.map {|var| instance_variable_get(var)},
213 # Reinitializes delegation from a serialized object.
215 def marshal_load(data)
216 version, vars, values, obj = data
217 if version == :__v2__
218 vars.each_with_index {|var, i| instance_variable_set(var, values[i])}
225 def initialize_clone(obj, freeze: nil) # :nodoc:
226 self.__setobj__(obj.__getobj__.clone(freeze: freeze))
228 def initialize_dup(obj) # :nodoc:
229 self.__setobj__(obj.__getobj__.dup)
231 private :initialize_clone, :initialize_dup
235 # Freeze both the object returned by \_\_getobj\_\_ and self.
242 @delegator_api = self.public_instance_methods
243 def self.public_api # :nodoc:
249 # A concrete implementation of Delegator, this class provides the means to
250 # delegate all supported method calls to the object passed into the constructor
251 # and even to change the object being delegated to at a later time with
256 # Date.new(1989, 9, 10)
262 # class UserDecorator < SimpleDelegator
268 # decorated_user = UserDecorator.new(User.new)
269 # decorated_user.birth_year #=> 1989
270 # decorated_user.__getobj__ #=> #<User: ...>
272 # A SimpleDelegator instance can take advantage of the fact that SimpleDelegator
273 # is a subclass of +Delegator+ to call <tt>super</tt> to have methods called on
274 # the object being delegated to.
276 # class SuperArray < SimpleDelegator
282 # SuperArray.new([1])[0] #=> 2
284 # Here's a simple example that takes advantage of the fact that
285 # SimpleDelegator's delegation object can be changed at any time.
289 # @source = SimpleDelegator.new([])
293 # @source.__setobj__(records)
295 # "Elements: #{@source.size}\n" +
296 # " Non-Nil: #{@source.compact.size}\n" +
297 # " Unique: #{@source.uniq.size}\n"
302 # puts s.stats(%w{James Edward Gray II})
304 # puts s.stats([1, 2, 3, nil, 4, 5, 1, 2])
316 class SimpleDelegator < Delegator
317 # Returns the current object method calls are being delegated to.
319 unless defined?(@delegate_sd_obj)
320 return yield if block_given?
321 __raise__ ::ArgumentError, "not delegated"
327 # Changes the delegate object to _obj_.
329 # It's important to note that this does *not* cause SimpleDelegator's methods
330 # to change. Because of this, you probably only want to change delegation
331 # to objects of the same type as the original delegate.
333 # Here's an example of changing the delegation object.
335 # names = SimpleDelegator.new(%w{James Edward Gray II})
336 # puts names[1] # => Edward
337 # names.__setobj__(%w{Gavin Sinclair})
338 # puts names[1] # => Sinclair
341 __raise__ ::ArgumentError, "cannot delegate to self" if self.equal?(obj)
342 @delegate_sd_obj = obj
346 def Delegator.delegating_block(mid) # :nodoc:
347 lambda do |*args, &block|
348 target = self.__getobj__
349 target.__send__(mid, *args, &block)
354 # The primary interface to this library. Use to setup delegation when defining
357 # class MyClass < DelegateClass(ClassToDelegateTo) # Step 1
359 # super(obj_of_ClassToDelegateTo) # Step 2
365 # MyClass = DelegateClass(ClassToDelegateTo) do # Step 1
367 # super(obj_of_ClassToDelegateTo) # Step 2
371 # Here's a sample of use from Tempfile which is really a File object with a
372 # few special rules about storage location and when the File should be
373 # deleted. That makes for an almost textbook perfect example of how to use
376 # class Tempfile < DelegateClass(File)
377 # # constant and class member data initialization...
379 # def initialize(basename, tmpdir=Dir::tmpdir)
380 # # build up file path/name in var tmpname...
382 # @tmpfile = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL, 0600)
388 # # below this point, all methods of File are supported...
394 def DelegateClass(superclass, &block)
395 klass = Class.new(Delegator)
396 ignores = [*::Delegator.public_api, :to_s, :inspect, :=~, :!~, :===]
397 protected_instance_methods = superclass.protected_instance_methods
398 protected_instance_methods -= ignores
399 public_instance_methods = superclass.public_instance_methods
400 public_instance_methods -= ignores
402 def __getobj__ # :nodoc:
403 unless defined?(@delegate_dc_obj)
404 return yield if block_given?
405 __raise__ ::ArgumentError, "not delegated"
409 def __setobj__(obj) # :nodoc:
410 __raise__ ::ArgumentError, "cannot delegate to self" if self.equal?(obj)
411 @delegate_dc_obj = obj
413 protected_instance_methods.each do |method|
414 define_method(method, Delegator.delegating_block(method))
417 public_instance_methods.each do |method|
418 define_method(method, Delegator.delegating_block(method))
421 klass.define_singleton_method :public_instance_methods do |all=true|
422 super(all) | superclass.public_instance_methods
424 klass.define_singleton_method :protected_instance_methods do |all=true|
425 super(all) | superclass.protected_instance_methods
427 klass.define_singleton_method :instance_methods do |all=true|
428 super(all) | superclass.instance_methods
430 klass.define_singleton_method :public_instance_method do |name|
433 raise unless self.public_instance_methods.include?(name)
434 superclass.public_instance_method(name)
436 klass.define_singleton_method :instance_method do |name|
439 raise unless self.instance_methods.include?(name)
440 superclass.instance_method(name)
442 klass.module_eval(&block) if block