Skip to content
This repository
Browse code

Document Active Support's Module::delegate. Closes #5002.

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4329 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
commit befd62c2fc04356980c4de493ffdee40e7a36c87 1 parent 0adcd81
Jeremy Kemper jeremy authored
2  activesupport/CHANGELOG
... ... @@ -1,5 +1,7 @@
1 1 *SVN*
2 2
  3 +* Document Module::delegate. #5002 [pergesu@gmail.com]
  4 +
3 5 * Replace alias method chaining with Module#alias_method_chain. [Marcel Molina Jr.]
4 6
5 7 * Strip out punctuation on predicates or bang methods being aliased with alias_method_chain since target?_without_feature is not a valid method name. Add tests for Module#alias_method_chain. [Marcel Molina Jr.]
29 activesupport/lib/active_support/core_ext/module/delegation.rb
... ... @@ -1,8 +1,33 @@
1 1 class Module
  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 :to option (also a symbol
  5 + # or string). At least one method and the :to option are required.
  6 + #
  7 + # Delegation is particularly useful with Active Record associations:
  8 + # class Greeter < ActiveRecord::Base
  9 + # def hello() "hello" end
  10 + # def goodbye() "goodbye" end
  11 + # end
  12 + #
  13 + # class Foo < ActiveRecord::Base
  14 + # belongs_to :greeter
  15 + # delegate :hello, :to => :greeter
  16 + # end
  17 + #
  18 + # Foo.new.hello # => "hello"
  19 + # Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c>
  20 + #
  21 + # With multiple delegates to the same target are allowed:
  22 + # class Foo < ActiveRecord::Base
  23 + # delegate :hello, :goodbye, :to => :greeter
  24 + # end
  25 + #
  26 + # Foo.new.goodbye # => "goodbye"
2 27 def delegate(*methods)
3 28 options = methods.pop
4 29 unless options.is_a?(Hash) && to = options[:to]
5   - raise ArgumentError, "Delegation needs a target. Supply an options hash with a :to key"
  30 + raise ArgumentError, "Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, :to => :greeter)."
6 31 end
7 32
8 33 methods.each do |method|
@@ -13,4 +38,4 @@ def #{method}(*args, &block)
13 38 EOS
14 39 end
15 40 end
16   -end
  41 +end

0 comments on commit befd62c

Please sign in to comment.
Something went wrong with that request. Please try again.