aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/module/delegation.rb
diff options
context:
space:
mode:
authorSergio Gil <sgilperez@gmail.com>2008-12-08 00:53:38 +0100
committerPratik Naik <pratiknaik@gmail.com>2008-12-21 23:24:06 +0000
commite8de7a67a5ef063164da022845a7cae1753da80e (patch)
tree6b9f49120dd9f95b4b5800454520bf1cc4dcf793 /activesupport/lib/active_support/core_ext/module/delegation.rb
parentf7bd0beb67c5d9d50e37aa596605b91e61197fbe (diff)
downloadrails-e8de7a67a5ef063164da022845a7cae1753da80e.tar.gz
rails-e8de7a67a5ef063164da022845a7cae1753da80e.tar.bz2
rails-e8de7a67a5ef063164da022845a7cae1753da80e.zip
Add :allow_nil option to delegate [#1127 state:resolved]
Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
Diffstat (limited to 'activesupport/lib/active_support/core_ext/module/delegation.rb')
-rw-r--r--activesupport/lib/active_support/core_ext/module/delegation.rb28
1 files changed, 27 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 2905eebc85..5c75bd4938 100644
--- a/activesupport/lib/active_support/core_ext/module/delegation.rb
+++ b/activesupport/lib/active_support/core_ext/module/delegation.rb
@@ -72,6 +72,30 @@ class Module
# invoice.customer_name # => "John Doe"
# invoice.customer_address # => "Vimmersvej 13"
#
+ # If the object to which you delegate can be nil, you may want to use the
+ # :allow_nil option. In that case, it returns nil instead of raising a
+ # NoMethodError exception:
+ #
+ # class Foo
+ # attr_accessor :bar
+ # def initialize(bar = nil)
+ # @bar = bar
+ # end
+ # delegate :zoo, :to => :bar
+ # end
+ #
+ # Foo.new.zoo # raises NoMethodError exception (you called nil.zoo)
+ #
+ # class Foo
+ # attr_accessor :bar
+ # def initialize(bar = nil)
+ # @bar = bar
+ # end
+ # delegate :zoo, :to => :bar, :allow_nil => true
+ # end
+ #
+ # Foo.new.zoo # returns nil
+ #
def delegate(*methods)
options = methods.pop
unless options.is_a?(Hash) && to = options[:to]
@@ -84,10 +108,12 @@ class Module
prefix = options[:prefix] && "#{options[:prefix] == true ? to : options[:prefix]}_"
+ allow_nil = options[:allow_nil] && "#{to} && "
+
methods.each do |method|
module_eval(<<-EOS, "(__DELEGATION__)", 1)
def #{prefix}#{method}(*args, &block)
- #{to}.__send__(#{method.inspect}, *args, &block)
+ #{allow_nil}#{to}.__send__(#{method.inspect}, *args, &block)
end
EOS
end