Forward and Delegate, A Simple Pattern (2007-08-11)
Here’s a simple example showing how to:- Forward all missing method invocations on to some @object
- Dynamically add delegation of that method to that object for future invocations
<notextile> def method_missing(meth, *args, &block) #:nodoc: returning @object.__send__(meth, *args, &block) do self.class.class_eval %{delegate :#{meth}, :to => :@object} end end </notextile>
- returning to avoid explicitly setting a temporary variable for the return value (stylistic choice of mine)
- delegate to generate the delegation code (because it’s dull to do it yourself)
Enjoy!


