2 # Provides a delegate class method to easily expose contained objects' methods
3 # as your own. Pass one or more methods (specified as symbols or strings)
4 # and the name of the target object as the final <tt>:to</tt> option (also a symbol
5 # or string). At least one method and the <tt>:to</tt> option are required.
7 # Delegation is particularly useful with Active Record associations:
9 # class Greeter < ActiveRecord::Base
10 # def hello() "hello" end
11 # def goodbye() "goodbye" end
14 # class Foo < ActiveRecord::Base
16 # delegate :hello, :to => :greeter
19 # Foo.new.hello # => "hello"
20 # Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c>
22 # Multiple delegates to the same target are allowed:
24 # class Foo < ActiveRecord::Base
26 # delegate :hello, :goodbye, :to => :greeter
29 # Foo.new.goodbye # => "goodbye"
31 # Methods can be delegated to instance variables, class variables, or constants
32 # by providing them as a symbols:
35 # CONSTANT_ARRAY = [0,1,2,3]
36 # @@class_array = [4,5,6,7]
39 # @instance_array = [8,9,10,11]
41 # delegate :sum, :to => :CONSTANT_ARRAY
42 # delegate :min, :to => :@@class_array
43 # delegate :max, :to => :@instance_array
50 # Delegates can optionally be prefixed using the <tt>:prefix</tt> option. If the value
51 # is <tt>true</tt>, the delegate methods are prefixed with the name of the object being
54 # Person = Struct.new(:name, :address)
56 # class Invoice < Struct.new(:client)
57 # delegate :name, :address, :to => :client, :prefix => true
60 # john_doe = Person.new("John Doe", "Vimmersvej 13")
61 # invoice = Invoice.new(john_doe)
62 # invoice.client_name # => "John Doe"
63 # invoice.client_address # => "Vimmersvej 13"
65 # It is also possible to supply a custom prefix.
67 # class Invoice < Struct.new(:client)
68 # delegate :name, :address, :to => :client, :prefix => :customer
71 # invoice = Invoice.new(john_doe)
72 # invoice.customer_name # => "John Doe"
73 # invoice.customer_address # => "Vimmersvej 13"
75 def delegate(*methods
)
77 unless options
.is_a
?(Hash
) && to
= options
[:to]
78 raise ArgumentError
, "Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, :to => :greeter)."
81 if options
[:prefix] == true && options
[:to].to_s
=~
/^[^a-z_]/
82 raise ArgumentError
, "Can only automatically set the delegation prefix when delegating to a method."
85 prefix
= options
[:prefix] && "#{options[:prefix] == true ? to : options[:prefix]}_"
87 methods
.each
do |method
|
88 module_eval(<<-EOS, "(__DELEGATION__)", 1)
89 def #{prefix}#{method}(*args, &block)
90 #{to}.__send__(#{method.inspect}, *args, &block)