Flowdock
method

delegate_missing_to

Importance_2
Ruby on Rails latest stable (v5.2.3) - 0 notes - Class: Module
delegate_missing_to(target) public

When building decorators, a common pattern may emerge:

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

  def person
    @event.detail.person || @event.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
    @event.detail.person || @event.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 NoMethodError.

Show source
Register or log in to add new notes.