Skip to content
Tutorials Center
My learning

Topics

Lesson 88 of 134 ยท Standard Library

Forwardable and Delegation

Learn delegation in Ruby - Forwardable's def_delegators, SimpleDelegator and DelegateClass decorators, composition vs inheritance, and the pitfalls with equality, is_a? and private methods.

Sometimes one object should hand work to another. A Playlist has a list of songs, and users should be able to ask the playlist for its size or loop over it, but the playlist is not a kind of Array (it should not have shuffle! or concat just because arrays do). A LoggedAccount wants everything a normal account can do plus a line in a log. This pattern of passing calls on to a helper object is called delegation, and it is the standard way to reuse behaviour without inheritance, the principle "composition over inheritance" from Design Principles in Ruby.

You can write delegation by hand (and it is good to see that once), but Ruby's standard library has two tools that remove the boilerplate. Forwardable declares which methods are passed to which target. Delegator (with SimpleDelegator and DelegateClass) makes an object that behaves like another one and lets you add or change a few methods, which is the decorator pattern. Both load with require and ship with Ruby.

Delegation by hand

Start with the problem. A Playlist that exposes a few array operations:

Ruby Manual delegation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

It works, and it keeps the interface small: shuffle! is not available. But every method is four lines of identical plumbing. With ten forwarded methods it is noise that hides what the class really does. That is what Forwardable is for.

Forwardable

extend Forwardable adds class-level macros. def_delegators :target, :method1, :method2 defines instance methods that call the same-named method on the target.

Ruby def_delegator and def_delegators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

What happened:

  • The target (:@songs) can be an instance variable, a method name (:address), or a string with any Ruby expression ("self.class").
  • def_delegator target, method, alias forwards one method, optionally under a new name (last became final_song).
  • The forwarded methods are real methods defined on your class: instance_method(:size).owner is Playlist, and respond_to?(:size) is true. That is different from method_missing approaches, and it is why Forwardable is fast and transparent.
  • Forwarding only each and including Enumerable gives you map, sort, select and the rest.
  • There is also a shorter hash form: delegate [:push, :pop, :size] => :@items or delegate peek: :@items, and instance_delegate as a synonym.

Arguments, keyword arguments and blocks are all passed along, and the result of the target is returned as is.

Delegating to a method

A target need not be an instance variable. Forward through any method of your class, which is useful for the "law of Demeter" (talk only to your direct neighbours):

Ruby Delegating through an association

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

ada.city reads better than ada.address.city, and callers are not tied to the fact that addresses exist as separate objects. Only the methods you list are forwarded; street is not.

What can go wrong

The target is evaluated every time. If the instance variable is nil or the target has no such method, the error comes from the target, and the message names the target's class, not yours:

Ruby Delegating to nil (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The run prints a warning first (main.rb:12: warning: Counter#size at .../forwardable.rb:159 forwarding to private method NilClass#size) and then ends with undefined method 'size' for nil (NoMethodError). The fix is to make sure the target exists (initialize @values = []). Typos in the forwarded method name fail the same way, at the first call and not when the class is defined, so cover every forwarded method with a test (see Testing with Minitest).

SimpleDelegator: wrap and decorate

Forwardable forwards a list of methods you name. SimpleDelegator forwards everything it does not define itself, to the object it wraps. You subclass it, add or override a few methods, and call super to reach the wrapped behaviour. This is how you build decorators: extra behaviour layered on an object without changing its class.

Ruby A decorator with SimpleDelegator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

__getobj__ returns the wrapped object and __setobj__ swaps it. Inside the subclass, plain method calls such as first reach the wrapped user too, and super inside an overriding method calls the wrapped object's version. The presenter keeps display logic (full_name) out of the data class, a typical use in web applications.

Add behaviour around every call, such as timing or logging, by defining method_missing on top of the delegator, or just override the methods you care about. Here is a logging decorator for a collection:

Ruby Wrapping to add logging

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Look closely at the log. The array finally holds [1, 3] (the 2 was added and then deleted), but the log has added 1, added 3 and deleted 2: the 2 from list << 1 << 2 was never logged. The reason: the wrapper's << ends with super, which returns what Array#<< returns, the wrapped array itself, so the second << of the chain hit the plain array and bypassed the decorator. Return self from your wrapper methods if chaining should stay inside the decorator.

The identity trap

A delegator is not the object it wraps; it only imitates it. That surfaces in a few places:

Ruby What a delegator is and is not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The wrapper answers respond_to?, forwards == in one direction only, and says it is not an Array or User. So case/when on classes, is_a? checks, and user == view can behave unexpectedly. Rules of thumb: do not compare wrapped objects with the wrapper on the right-hand side, unwrap with __getobj__ when you need the real type, and avoid type checks (use duck typing).

Another surprise is visibility: a delegator forwards only public methods. Calling a private method of the wrapped object raises NoMethodError (for example undefined method 'secret' for an instance of SimpleDelegator), and that is usually what you want.

DelegateClass: delegate to a known class

SimpleDelegator discovers methods at call time. When you know the class you wrap, DelegateClass(Array) builds a delegator class with all of that class's public instance methods defined up front:

Ruby DelegateClass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The class you inherit from is an anonymous delegating class sitting between History and Delegator, as the ancestors show. You get a class that offers all Array methods but is not an Array. As with SimpleDelegator, the wrapper reports is_a?(Array) as false.

Choosing a tool

You want Use
Expose a few methods of a collaborator under your own interface Forwardable (def_delegators)
Add or tweak behaviour of one object, keep the rest SimpleDelegator subclass (decorator)
The same, but with a fixed known class DelegateClass(SomeClass)
Is-a relationship with all inherited behaviour Plain inheritance (see Inheritance)
Catch-all forwarding with your own logic method_missing (see method_missing and respond_to_missing?)

Some practical notes:

  • Forwardable defines real methods, so there is no extra lookup magic. Delegator objects forward through method_missing, which is a little slower and shows up in error messages, so avoid them in the hottest loops.
  • Delegating less is better. The point of composition is a narrow interface. Forwarding forty methods rebuilds inheritance with more typing.
  • Hand-written is fine for one or two methods. Writing def size = @songs.size (see Endless Methods and Modern Syntax) is clear and needs no library.
  • You can write your own macro with define_method in a dozen lines, which is how Rails' delegate works (read-only here; it adds options such as allow_nil and prefix).
Ruby A homemade delegate macro

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Adding forward to Module is a small example of monkey patching; a real project would put it in its own module and extend it into the classes that need it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does def_delegators :@songs, :size, :each do inside a class that extends Forwardable?

    Forwardable defines real instance methods that pass the call, with arguments and block, to the target and return its result.
  2. 2. Which statement about SimpleDelegator.new([1, 2]).is_a?(Array) is true?

    A delegator forwards method calls but keeps its own class. Use getobj when you need the wrapped object's real type.
  3. 3. In a class Decorator < SimpleDelegator, what does super do inside def price?

    The delegator's method_missing forwards the call, so super inside an override reaches the wrapped object's method.
  4. 4. When is plain Forwardable a better fit than SimpleDelegator?

    Forwardable names each forwarded method, giving a narrow interface. SimpleDelegator forwards everything the wrapper does not define.
  5. 5. A class forwards size to @values, but @values was never set. What happens when size is called?

    The forwarding method calls size on nil, which does not have it. Initialize the target so the delegation has something to talk to.

Summary

  • Delegation passes work to a helper object; it gives reuse without inheriting the helper's whole interface.
  • Forwardable (def_delegator, def_delegators, delegate) defines real forwarding methods; targets can be instance variables, methods or expressions.
  • SimpleDelegator wraps an object and forwards everything it does not define, ideal for decorators; use super, __getobj__ and __setobj__.
  • DelegateClass(Klass) builds a delegator for a known class.
  • A delegator is not the object it wraps: is_a?, Klass === obj, case/when and reversed == behave differently, and private methods are not forwarded.
  • Return self from decorator methods when chaining should stay on the wrapper, keep the forwarded interface small, and test each forwarded method.

Next: Observable, Singleton and Standard Patterns