1 # frozen_string_literal: false
4 # $Release Version: 1.1$
6 # by Keiju ISHITSUKA(keiju@ishitsuka.com)
7 # original definition by delegator.rb
8 # Revised by Daniel J. Berger with suggestions from Florian Gross.
10 # Documentation by James Edward Gray II and Gavin Sinclair
14 # The Forwardable module provides delegation of specified
15 # methods to a designated object, using the methods #def_delegator
16 # and #def_delegators.
18 # For example, say you have a class RecordCollection which
19 # contains an array <tt>@records</tt>. You could provide the lookup method
20 # #record_number(), which simply calls #[] on the <tt>@records</tt>
23 # require 'forwardable'
25 # class RecordCollection
26 # attr_accessor :records
28 # def_delegator :@records, :[], :record_number
31 # We can use the lookup method like so:
33 # r = RecordCollection.new
35 # r.record_number(0) # => 4
37 # Further, if you wish to provide the methods #size, #<<, and #map,
38 # all of which delegate to @records, this is how you can do it:
40 # class RecordCollection # re-open RecordCollection class
41 # def_delegators :@records, :size, :<<, :map
44 # r = RecordCollection.new
46 # r.record_number(0) # => 1
48 # r << 4 # => [1, 2, 3, 4]
49 # r.map { |x| x * 2 } # => [2, 4, 6, 8]
51 # You can even extend regular objects with Forwardable.
54 # my_hash.extend Forwardable # prepare object for delegation
55 # my_hash.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts()
56 # my_hash.puts "Howdy!"
60 # You could use Forwardable as an alternative to inheritance, when you don't want
61 # to inherit all methods from the superclass. For instance, here is how you might
62 # add a range of +Array+ instance methods to a new class +Queue+:
68 # @q = [ ] # prepare delegate object
71 # # setup preferred interface, enq() and deq()...
72 # def_delegator :@q, :push, :enq
73 # def_delegator :@q, :shift, :deq
75 # # support some general Array methods that fit Queues well
76 # def_delegators :@q, :clear, :first, :push, :shift, :size
79 # q = Thread::Queue.new
88 # q.enq "Ruby", "Perl", "Python"
105 # Be advised, RDoc will not detect delegated methods.
107 # +forwardable.rb+ provides single-method delegation via the def_delegator and
108 # def_delegators methods. For full-class delegation via DelegateClass, see
112 require 'forwardable/impl'
114 # Version of +forwardable.rb+
117 FORWARDABLE_VERSION = VERSION
118 FORWARDABLE_VERSION.freeze
126 # Takes a hash as its argument. The key is a symbol or an array of
127 # symbols. These symbols correspond to method names, instance variable
128 # names, or constant names (see def_delegator). The value is
129 # the accessor to which the methods will be delegated.
132 # delegate method => accessor
133 # delegate [method, method, ...] => accessor
135 def instance_delegate(hash)
136 hash.each do |methods, accessor|
137 unless defined?(methods.each)
138 def_instance_delegator(accessor, methods)
140 methods.each {|method| def_instance_delegator(accessor, method)}
146 # Shortcut for defining multiple delegator methods, but with no
147 # provision for using a different name. The following two code
148 # samples have the same effect:
150 # def_delegators :@records, :size, :<<, :map
152 # def_delegator :@records, :size
153 # def_delegator :@records, :<<
154 # def_delegator :@records, :map
156 def def_instance_delegators(accessor, *methods)
157 methods.each do |method|
158 next if /\A__(?:send|id)__\z/ =~ method
159 def_instance_delegator(accessor, method)
163 # Define +method+ as delegator instance method with an optional
164 # alias name +ali+. Method calls to +ali+ will be delegated to
165 # +accessor.method+. +accessor+ should be a method name, instance
166 # variable name, or constant name. Use the full path to the
167 # constant if providing the constant name.
168 # Returns the name of the method defined.
178 # def_delegator :@queue, :push, :mypush
179 # def_delegator 'MyQueue::CONST', :to_i
185 # q.push 23 #=> NoMethodError
188 def def_instance_delegator(accessor, method, ali = method)
189 gen = Forwardable._delegator_method(self, accessor, method, ali)
191 # If it's not a class or module, it's an instance
192 mod = Module === self ? self : singleton_class
193 ret = mod.module_eval(&gen)
194 mod.__send__(:ruby2_keywords, ali) if RUBY_VERSION >= '2.7'
198 alias delegate instance_delegate
199 alias def_delegators def_instance_delegators
200 alias def_delegator def_instance_delegator
203 def self._delegator_method(obj, accessor, method, ali)
204 accessor = accessor.to_s unless Symbol === accessor
207 obj.method_defined?(accessor) || obj.private_method_defined?(accessor) :
208 obj.respond_to?(accessor, true)
209 accessor = "#{accessor}()"
212 method_call = ".__send__(:#{method}, *args, &block)"
213 if _valid_method?(method)
214 loc, = caller_locations(2,1)
216 mesg = "#{Module === obj ? obj : obj.class}\##{ali} at #{loc.path}:#{loc.lineno} forwarding to private method "
217 method_call = "#{<<-"begin;"}\n#{<<-"end;".chomp}"
219 unless defined? _.#{method}
220 ::Kernel.warn #{mesg.dump}"\#{_.class}"'##{method}', uplevel: 1
223 _.#{method}(*args, &block)
228 _compile_method("#{<<-"begin;"}\n#{<<-"end;"}", __FILE__, __LINE__+1)
231 def #{ali}(*args, &block)
242 # SingleForwardable can be used to setup delegation at the object level as well.
244 # printer = String.new
245 # printer.extend SingleForwardable # prepare object for delegation
246 # printer.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts()
247 # printer.puts "Howdy!"
249 # Also, SingleForwardable can be used to set up delegation for a Class or Module.
251 # class Implementation
258 # extend SingleForwardable
259 # def_delegator :Implementation, :service
262 # Facade.service #=> serviced!
264 # If you want to use both Forwardable and SingleForwardable, you can
265 # use methods def_instance_delegator and def_single_delegator, etc.
266 module SingleForwardable
267 # Takes a hash as its argument. The key is a symbol or an array of
268 # symbols. These symbols correspond to method names. The value is
269 # the accessor to which the methods will be delegated.
272 # delegate method => accessor
273 # delegate [method, method, ...] => accessor
275 def single_delegate(hash)
276 hash.each do |methods, accessor|
277 unless defined?(methods.each)
278 def_single_delegator(accessor, methods)
280 methods.each {|method| def_single_delegator(accessor, method)}
286 # Shortcut for defining multiple delegator methods, but with no
287 # provision for using a different name. The following two code
288 # samples have the same effect:
290 # def_delegators :@records, :size, :<<, :map
292 # def_delegator :@records, :size
293 # def_delegator :@records, :<<
294 # def_delegator :@records, :map
296 def def_single_delegators(accessor, *methods)
297 methods.each do |method|
298 next if /\A__(?:send|id)__\z/ =~ method
299 def_single_delegator(accessor, method)
304 # def_single_delegator(accessor, method, new_name=method)
306 # Defines a method _method_ which delegates to _accessor_ (i.e. it calls
307 # the method of the same name in _accessor_). If _new_name_ is
308 # provided, it is used as the name for the delegate method.
309 # Returns the name of the method defined.
310 def def_single_delegator(accessor, method, ali = method)
311 gen = Forwardable._delegator_method(self, accessor, method, ali)
313 ret = instance_eval(&gen)
314 singleton_class.__send__(:ruby2_keywords, ali) if RUBY_VERSION >= '2.7'
318 alias delegate single_delegate
319 alias def_delegators def_single_delegators
320 alias def_delegator def_single_delegator