Fork me on GitHub

Forward and Delegate, A Simple Pattern

2007-08-11

Here’s a simple example showing how to:

  1. Forward all missing method invocations on to some object

  2. Dynamically add delegation of that method to that object for future invocation.

    def methodmissing(meth, args, &block) #:nodoc: returning @object.send(meth,args, &block) do self.class.classeval %{delegate :#{meth}, :to => :@object} end end

Note this example uses two bits from ActiveSupport:

  1. returning to avoid explicitly setting a temporary variable for the return value (stylistic choice of mine)
  2. delegate to generate the delegation code (because it’s dull to do it yourself)

Enjoy!

Discussion