delegate_missing_to
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7 (0)
- 5.2.3 (-35)
- 6.0.0 (38)
- 6.1.3.1 (13)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (0)
- 7.1.3.4 (0)
- What's this?
delegate_missing_to(target, allow_nil: nil)
public
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 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.