From e8de7a67a5ef063164da022845a7cae1753da80e Mon Sep 17 00:00:00 2001 From: Sergio Gil Date: Mon, 8 Dec 2008 00:53:38 +0100 Subject: Add :allow_nil option to delegate [#1127 state:resolved] Signed-off-by: Pratik Naik --- .../active_support/core_ext/module/delegation.rb | 28 +++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) (limited to 'activesupport/lib') 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 -- cgit v1.2.3