|
19 | 19 | # #record_number(), which simply calls #[] on the <tt>@records</tt>
|
20 | 20 | # array, like this:
|
21 | 21 | #
|
| 22 | +# require 'forwardable' |
| 23 | +# |
22 | 24 | # class RecordCollection
|
| 25 | +# attr_accessor :records |
23 | 26 | # extend Forwardable
|
24 | 27 | # def_delegator :@records, :[], :record_number
|
25 | 28 | # end
|
26 | 29 | #
|
| 30 | +# We can use the lookup method like so: |
| 31 | +# |
| 32 | +# r = RecordCollection.new |
| 33 | +# r.records = [4,5,6] |
| 34 | +# r.record_number(0) # => 4 |
| 35 | +# |
27 | 36 | # Further, if you wish to provide the methods #size, #<<, and #map,
|
28 | 37 | # all of which delegate to @records, this is how you can do it:
|
29 | 38 | #
|
30 |
| -# class RecordCollection |
31 |
| -# # extend Forwardable, but we did that above |
| 39 | +# class RecordCollection # re-open RecordCollection class |
32 | 40 | # def_delegators :@records, :size, :<<, :map
|
33 | 41 | # end
|
34 |
| -# f = Foo.new |
35 |
| -# f.printf ... |
36 |
| -# f.gets |
37 |
| -# f.content_at(1) |
38 |
| -# |
39 |
| -# If the object isn't a Module and Class, You can too extend Forwardable |
40 |
| -# module. |
41 |
| -# |
42 |
| -# printer = String.new |
43 |
| -# printer.extend Forwardable # prepare object for delegation |
44 |
| -# printer.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts() |
45 |
| -# printer.puts "Howdy!" |
| 42 | +# |
| 43 | +# r = RecordCollection.new |
| 44 | +# r.records = [1,2,3] |
| 45 | +# r.record_number(0) # => 1 |
| 46 | +# r.size # => 3 |
| 47 | +# r << 4 # => [1, 2, 3, 4] |
| 48 | +# r.map { |x| x * 2 } # => [2, 4, 6, 8] |
| 49 | +# |
| 50 | +# You can even extend regular objects with Forwardable. |
| 51 | +# |
| 52 | +# my_hash = Hash.new |
| 53 | +# my_hash.extend Forwardable # prepare object for delegation |
| 54 | +# my_hash.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts() |
| 55 | +# my_hash.puts "Howdy!" |
46 | 56 | #
|
47 | 57 | # == Another example
|
48 | 58 | #
|
|
0 commit comments