diff options
author | Ryan Bigg <radarlistener@gmail.com> | 2008-10-22 21:46:49 +1030 |
---|---|---|
committer | Ryan Bigg <radarlistener@gmail.com> | 2008-10-22 21:46:49 +1030 |
commit | 4a53eb8a79e3e0535ba19e6da38370a542ce4961 (patch) | |
tree | 965418cb69895e44879c7b1fa428e808b91aa66a /activesupport/lib/active_support/core_ext | |
parent | a325010d6c9b2c69cab5da046e1106aad491b73f (diff) | |
parent | 303919c62660c68ca450a53ec5ef29ec2c615b7a (diff) | |
download | rails-4a53eb8a79e3e0535ba19e6da38370a542ce4961.tar.gz rails-4a53eb8a79e3e0535ba19e6da38370a542ce4961.tar.bz2 rails-4a53eb8a79e3e0535ba19e6da38370a542ce4961.zip |
Merge branch 'master' of git@github.com:lifo/docrails
Diffstat (limited to 'activesupport/lib/active_support/core_ext')
-rw-r--r-- | activesupport/lib/active_support/core_ext/module/delegation.rb | 29 |
1 files changed, 28 insertions, 1 deletions
diff --git a/activesupport/lib/active_support/core_ext/module/delegation.rb b/activesupport/lib/active_support/core_ext/module/delegation.rb index e0b5f3e379..1ad18402e5 100644 --- a/activesupport/lib/active_support/core_ext/module/delegation.rb +++ b/activesupport/lib/active_support/core_ext/module/delegation.rb @@ -47,15 +47,42 @@ class Module # Foo.new.min # => 4 # Foo.new.max # => 11 # + # Delegates can optionally be prefixed using the <tt>:prefix</tt> option. If the value + # is <tt>true</tt>, the delegate methods are prefixed with the name of the object being + # delegated to. + # + # Person = Struct.new(:name, :address) + # + # class Invoice < Struct.new(:client) + # delegate :name, :address, :to => :client, :prefix => true + # end + # + # john_doe = Person.new("John Doe", "Vimmersvej 13") + # invoice = Invoice.new(john_doe) + # invoice.client_name # => "John Doe" + # invoice.client_address # => "Vimmersvej 13" + # + # It is also possible to supply a custom prefix. + # + # class Invoice < Struct.new(:client) + # delegate :name, :address, :to => :client, :prefix => :customer + # end + # + # invoice = Invoice.new(john_doe) + # invoice.customer_name # => "John Doe" + # invoice.customer_address # => "Vimmersvej 13" + # def delegate(*methods) options = methods.pop unless options.is_a?(Hash) && to = options[:to] raise ArgumentError, "Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, :to => :greeter)." end + prefix = options[:prefix] && "#{options[:prefix] == true ? to : options[:prefix]}_" + methods.each do |method| module_eval(<<-EOS, "(__DELEGATION__)", 1) - def #{method}(*args, &block) + def #{prefix}#{method}(*args, &block) #{to}.__send__(#{method.inspect}, *args, &block) end EOS |