From ccbe02343934956d3bb11c7167e0493f9d8f08fd Mon Sep 17 00:00:00 2001 From: Li Ellis Gallardo Date: Thu, 25 Apr 2013 17:00:13 -0500 Subject: [PATCH] Delegation method bug Add documentation and test to delegation method that make sure we're aware that when a delegated object is not nil or false and doesn't respond to the method it will still raise a NoMethodError exception. --- .../active_support/core_ext/module/delegation.rb | 14 ++++++++++++++ activesupport/test/core_ext/module_test.rb | 5 +++++ 2 files changed, 19 insertions(+) diff --git a/activesupport/lib/active_support/core_ext/module/delegation.rb b/activesupport/lib/active_support/core_ext/module/delegation.rb index e608eeaf420f4..c0828343d8e7e 100644 --- a/activesupport/lib/active_support/core_ext/module/delegation.rb +++ b/activesupport/lib/active_support/core_ext/module/delegation.rb @@ -112,6 +112,20 @@ class Module # end # # Foo.new.zoo # returns nil + # + # If the delegate object is not +nil+ or +false+ and the object doesn't + # respond to the delegated method it will raise an exception. + # + # class Foo + # def initialize(bar) + # @bar = bar + # end + # + # delegate :name, to: :@bar + # end + # + # Foo.new("Bar").name # raises NoMethodError: undefined method `name' + # def delegate(*methods) options = methods.pop unless options.is_a?(Hash) && to = options[:to] diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb index 82249ddd1b2f8..9a8582075dcee 100644 --- a/activesupport/test/core_ext/module_test.rb +++ b/activesupport/test/core_ext/module_test.rb @@ -171,6 +171,11 @@ def test_delegation_with_allow_nil_and_nil_value assert_nil rails.name end + def test_delegation_with_allow_nil_and_invalid_value + rails = Project.new("Rails", "David") + assert_raise(NoMethodError) { rails.name } + end + def test_delegation_with_allow_nil_and_nil_value_and_prefix Project.class_eval do delegate :name, :to => :person, :allow_nil => true, :prefix => true