Method: Module#delegate_missing_to

Defined in:
activesupport/lib/active_support/core_ext/module/delegation.rb

#delegate_missing_to(target, allow_nil: nil) ⇒ Object

When building decorators, a common pattern may emerge:

class Partition
def initialize(event)
  @event = event
end

def person
  detail.person || creator
end

private
  def respond_to_missing?(name, include_private = false)
    @event.respond_to?(name, include_private)
  end

  def method_missing(method, *args, &block)
    @event.send(method, *args, &block)
  end
end

With Module#delegate_missing_to, the above is condensed to:

class Partition
delegate_missing_to :@event

def initialize(event)
  @event = event
end

def person
  detail.person || creator
end
end

The target can be anything callable within the object, e.g. instance variables, methods, constants, etc.

The delegated method must be public on the target, otherwise it will raise ActiveSupport::DelegationError. If you wish to instead return nil, use the :allow_nil option.

The marshal_dump and _dump methods are exempt from delegation due to possible interference when calling Marshal.dump(object), should the delegation target method of object add or remove instance variables.



218
219
220
221
222
223
224
# File 'activesupport/lib/active_support/core_ext/module/delegation.rb', line 218

def delegate_missing_to(target, allow_nil: nil)
  ::ActiveSupport::Delegation.generate_method_missing(
    self,
    target,
    allow_nil: allow_nil,
  )
end