lib/forwardable.rb
DEFINITIONS
This source file includes following functions.
1 #
2 # forwardable.rb -
3 # $Release Version: 1.1$
4 # $Revision: 1.2 $
5 # $Date: 2001/11/03 13:41:57 $
6 # by Keiju ISHITSUKA(keiju@ishitsuka.com)
7 # original definition by delegator.rb
8 # --
9 # Usage:
10 #
11 # class Foo
12 # extend Forwardable
13 #
14 # def_delegators("@out", "printf", "print")
15 # def_delegators(:@in, :gets)
16 # def_delegator(:@contents, :[], "content_at")
17 # end
18 # f = Foo.new
19 # f.printf ...
20 # f.gets
21 # f.content_at(1)
22 #
23 # g = Goo.new
24 # g.extend SingleForwardable
25 # g.def_delegator("@out", :puts)
26 # g.puts ...
27 #
28 #
29
30 module Forwardable
31
32 @debug = nil
33 class<<self
34 attr_accessor :debug
35 end
36
37 def def_instance_delegators(accessor, *methods)
38 for method in methods
39 def_instance_delegator(accessor, method)
40 end
41 end
42
43 def def_instance_delegator(accessor, method, ali = method)
44 accessor = accessor.id2name if accessor.kind_of?(Integer)
45 method = method.id2name if method.kind_of?(Integer)
46 ali = ali.id2name if ali.kind_of?(Integer)
47
48 module_eval(<<-EOS, "(__FORWARDABLE__)", 1)
49 def #{ali}(*args, &block)
50 begin
51 #{accessor}.__send__(:#{method}, *args, &block)
52 rescue Exception
53 $@.delete_if{|s| /^\\(__FORWARDABLE__\\):/ =~ s} unless Forwardable::debug
54 Kernel::raise
55 end
56 end
57 EOS
58 end
59
60 alias def_delegators def_instance_delegators
61 alias def_delegator def_instance_delegator
62 end
63
64 module SingleForwardable
65 def def_singleton_delegators(accessor, *methods)
66 for method in methods
67 def_singleton_delegator(accessor, method)
68 end
69 end
70
71 def def_singleton_delegator(accessor, method, ali = method)
72 accessor = accessor.id2name if accessor.kind_of?(Integer)
73 method = method.id2name if method.kind_of?(Integer)
74 ali = ali.id2name if ali.kind_of?(Integer)
75
76 instance_eval(<<-EOS, "(__FORWARDABLE__)", 1)
77 def #{ali}(*args, &block)
78 begin
79 #{accessor}.__send__(:#{method}, *args,&block)
80 rescue Exception
81 $@.delete_if{|s| /^\\(__FORWARDABLE__\\):/ =~ s} unless Forwardable::debug
82 Kernel::raise
83 end
84 end
85 EOS
86 end
87
88 alias def_delegators def_singleton_delegators
89 alias def_delegator def_singleton_delegator
90 end
91
92
93
94