[rubygems/rubygems] Use a constant empty tar header to avoid extra allocations
[ruby.git] / lib / forwardable.rb
blob71b4e6adad4d9a792931413bbdaf624bcfbf60ce
1 # frozen_string_literal: false
3 #   forwardable.rb -
4 #       $Release Version: 1.1$
5 #       $Revision$
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>
21 # array, like this:
23 #   require 'forwardable'
25 #   class RecordCollection
26 #     attr_accessor :records
27 #     extend Forwardable
28 #     def_delegator :@records, :[], :record_number
29 #   end
31 # We can use the lookup method like so:
33 #   r = RecordCollection.new
34 #   r.records = [4,5,6]
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
42 #   end
44 #   r = RecordCollection.new
45 #   r.records = [1,2,3]
46 #   r.record_number(0)   # => 1
47 #   r.size               # => 3
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.
53 #   my_hash = Hash.new
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!"
58 # == Another example
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+:
64 #   class Queue
65 #     extend Forwardable
67 #     def initialize
68 #       @q = [ ]    # prepare delegate object
69 #     end
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
77 #   end
79 #   q = Thread::Queue.new
80 #   q.enq 1, 2, 3, 4, 5
81 #   q.push 6
83 #   q.shift    # => 1
84 #   while q.size > 0
85 #     puts q.deq
86 #   end
88 #   q.enq "Ruby", "Perl", "Python"
89 #   puts q.first
90 #   q.clear
91 #   puts q.first
93 # This should output:
95 #   2
96 #   3
97 #   4
98 #   5
99 #   6
100 #   Ruby
101 #   nil
103 # == Notes
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
109 # +delegate.rb+.
111 module Forwardable
112   require 'forwardable/impl'
114   # Version of +forwardable.rb+
115   VERSION = "1.3.3"
116   VERSION.freeze
117   FORWARDABLE_VERSION = VERSION
118   FORWARDABLE_VERSION.freeze
120   @debug = nil
121   class << self
122     # ignored
123     attr_accessor :debug
124   end
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.
130   #
131   # :call-seq:
132   #    delegate method => accessor
133   #    delegate [method, method, ...] => accessor
134   #
135   def instance_delegate(hash)
136     hash.each do |methods, accessor|
137       unless defined?(methods.each)
138         def_instance_delegator(accessor, methods)
139       else
140         methods.each {|method| def_instance_delegator(accessor, method)}
141       end
142     end
143   end
145   #
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:
149   #
150   #   def_delegators :@records, :size, :<<, :map
151   #
152   #   def_delegator :@records, :size
153   #   def_delegator :@records, :<<
154   #   def_delegator :@records, :map
155   #
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)
160     end
161   end
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.
169   #
170   #   class MyQueue
171   #     CONST = 1
172   #     extend Forwardable
173   #     attr_reader :queue
174   #     def initialize
175   #       @queue = []
176   #     end
177   #
178   #     def_delegator :@queue, :push, :mypush
179   #     def_delegator 'MyQueue::CONST', :to_i
180   #   end
181   #
182   #   q = MyQueue.new
183   #   q.mypush 42
184   #   q.queue    #=> [42]
185   #   q.push 23  #=> NoMethodError
186   #   q.to_i     #=> 1
187   #
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'
195     ret
196   end
198   alias delegate instance_delegate
199   alias def_delegators def_instance_delegators
200   alias def_delegator def_instance_delegator
202   # :nodoc:
203   def self._delegator_method(obj, accessor, method, ali)
204     accessor = accessor.to_s unless Symbol === accessor
206     if Module === obj ?
207          obj.method_defined?(accessor) || obj.private_method_defined?(accessor) :
208          obj.respond_to?(accessor, true)
209       accessor = "#{accessor}()"
210     end
212     method_call = ".__send__(:#{method}, *args, &block)"
213     if _valid_method?(method)
214       loc, = caller_locations(2,1)
215       pre = "_ ="
216       mesg = "#{Module === obj ? obj : obj.class}\##{ali} at #{loc.path}:#{loc.lineno} forwarding to private method "
217       method_call = "#{<<-"begin;"}\n#{<<-"end;".chomp}"
218         begin;
219           unless defined? _.#{method}
220             ::Kernel.warn #{mesg.dump}"\#{_.class}"'##{method}', uplevel: 1
221             _#{method_call}
222           else
223             _.#{method}(*args, &block)
224           end
225         end;
226     end
228     _compile_method("#{<<-"begin;"}\n#{<<-"end;"}", __FILE__, __LINE__+1)
229     begin;
230       proc do
231         def #{ali}(*args, &block)
232           #{pre}
233           begin
234             #{accessor}
235           end#{method_call}
236         end
237       end
238     end;
239   end
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
252 #     def self.service
253 #       puts "serviced!"
254 #     end
255 #   end
257 #   module Facade
258 #     extend SingleForwardable
259 #     def_delegator :Implementation, :service
260 #   end
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.
270   #
271   # :call-seq:
272   #    delegate method => accessor
273   #    delegate [method, method, ...] => accessor
274   #
275   def single_delegate(hash)
276     hash.each do |methods, accessor|
277       unless defined?(methods.each)
278         def_single_delegator(accessor, methods)
279       else
280         methods.each {|method| def_single_delegator(accessor, method)}
281       end
282     end
283   end
285   #
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:
289   #
290   #   def_delegators :@records, :size, :<<, :map
291   #
292   #   def_delegator :@records, :size
293   #   def_delegator :@records, :<<
294   #   def_delegator :@records, :map
295   #
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)
300     end
301   end
303   # :call-seq:
304   #   def_single_delegator(accessor, method, new_name=method)
305   #
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'
315     ret
316   end
318   alias delegate single_delegate
319   alias def_delegators def_single_delegators
320   alias def_delegator def_single_delegator