1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

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]
This commit is contained in:
Jared Beck 2017-02-03 17:22:24 -05:00
parent d13bc5df90
commit e014042bad

View file

@ -20,7 +20,8 @@ class Module
# ==== Options
# * <tt>:to</tt> - Specifies the target object
# * <tt>:prefix</tt> - Prefixes the new method with the target name or a custom prefix
# * <tt>:allow_nil</tt> - if set to true, prevents a +NoMethodError+ from being raised
# * <tt>:allow_nil</tt> - 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 <tt>:to</tt> 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
# <tt>:allow_nil</tt> 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 <tt>:allow_nil</tt> 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: