From e014042bad65b7d017b739124b7cd0e2d8f5105b Mon Sep 17 00:00:00 2001 From: Jared Beck Date: Fri, 3 Feb 2017 17:22:24 -0500 Subject: Docs: Correction: Module::DelegationError When the delegation target is nil and the allow_nil option is not in use, a Module::DelegationError is raised. class C delegate :a, to: :b def b nil end end C.new.a # => Module::DelegationError: C#a delegated to b.a, but b is nil [ci skip] --- .../lib/active_support/core_ext/module/delegation.rb | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/module/delegation.rb b/activesupport/lib/active_support/core_ext/module/delegation.rb index 19f692e943..d82758e40d 100644 --- a/activesupport/lib/active_support/core_ext/module/delegation.rb +++ b/activesupport/lib/active_support/core_ext/module/delegation.rb @@ -20,7 +20,8 @@ class Module # ==== Options # * :to - Specifies the target object # * :prefix - Prefixes the new method with the target name or a custom prefix - # * :allow_nil - if set to true, prevents a +NoMethodError+ from being raised + # * :allow_nil - if set to true, prevents a +Module::DelegationError+ + # from being raised # # The macro receives one or more method names (specified as symbols or # strings) and the name of the target object via the :to option @@ -112,18 +113,19 @@ class Module # invoice.customer_address # => 'Vimmersvej 13' # # If the target is +nil+ and does not respond to the delegated method a - # +NoMethodError+ is raised, as with any other value. Sometimes, however, it - # makes sense to be robust to that situation and that is the purpose of the - # :allow_nil option: If the target is not +nil+, or it is and - # responds to the method, everything works as usual. But if it is +nil+ and - # does not respond to the delegated method, +nil+ is returned. + # +Module::DelegationError+ is raised, as with any other value. Sometimes, + # however, it makes sense to be robust to that situation and that is the + # purpose of the :allow_nil option: If the target is not +nil+, or it + # is and responds to the method, everything works as usual. But if it is +nil+ + # and does not respond to the delegated method, +nil+ is returned. # # class User < ActiveRecord::Base # has_one :profile # delegate :age, to: :profile # end # - # User.new.age # raises NoMethodError: undefined method `age' + # User.new.age + # # => Module::DelegationError: User#age delegated to profile.age, but profile is nil # # But if not having a profile yet is fine and should not be an error # condition: -- cgit v1.2.3