Feature #13332

Forwardable#def_instance_delegator nil

Added by eike.rb (Eike Dierks) almost 4 years ago. Updated over 3 years ago.

Target version:


I'd like to suggest an extension to the signature of stdlib Forwardable#def_instance_delegator

currently (ruby 2.3.3) it is declared as:

  def_instance_delegator(accessor, method, ali = method)

I'd like to add a nil: option like this:

  def_instance_delegator(accessor, method, ali = method, nil_behaviour:NoMethodError)

As of ruby2.3, delegated methods fail with
#<NoMethodError: undefined methodfoo' for nil:NilClass>`
when the declared accessor returns nil

aka, when the delegator may be nil,
the Forwardable module can not be used,
but one has to ressort to implement the forward manually.

Adding an option to the signature could solve this.
I believe that this can be implemented in a fully backward compatible way.

I named this option :nil in my example,
(some people will cry out loud)

Specification scribble:

if accessor.nil?
  case nil_behaviour
  when nil then nil    # return nil, when accessor was nil
  when Error             # raise that Error with proper args
  when Proc             # invoke that Proc with proper args
  when String           # return that string
  else                        # return that object

Updated by nobu (Nobuyoshi Nakada) almost 4 years ago

  • Description updated (diff)

I wonder how common such case is.

And you can override delegator/accessor methods by yourself.

Updated by ko1 (Koichi Sasada) over 3 years ago

  • Assignee set to nobu (Nobuyoshi Nakada)

Updated by matz (Yukihiro Matsumoto) over 3 years ago

  • Status changed from Open to Feedback

The proposed solution seems to be too generic. Show us the use-case except for nil for nil'. For example, it is acceptable thatallow_nil: true` keyword argument we see in ActiveSupport.


Also available in: Atom PDF