hoodwink.d enhanced


Putting a Class in Foster Care #

by why in bits

Maybe you could call it “duck classing,” who knows. I think it fits. Subclassing any possible parent class that acts like a certain class. So, in MouseHole, I can swap out proxy backends I’m testing.

 def MouseHole.ProxyServer( proxy_base )
   Class.new( proxy_base ) do

     attr_accessor :user_scripts, :temp_scripts

     def initialize #.. and other overlaying methods


Pass in the base class and you get an anonymous class freshly built between the two.

 server = MouseHole.ProxyServer( WEBrick::HTTPProxyServer ).new

Ah, railroading inheritance. It’s like foster parents. Which is better than multiple inheritance (aka custody battles.) RIght?

said on 04 Oct 2005 at 17:13

In general it might be desirable to memoize such class factories:

class MouseHole
  @proxy_server_classes = {}
 def self.ProxyServer( proxy_base )
    @proxy_server_classes[ proxy_base ] ||=
      Class.new( proxy_base ) do
        # etc...

Either way, your approach effectively gets you that part of generic programming which duck typing doesn’t get for you.

If we lived in C++ land, which we don’t, but imagine that we do:

class MouseHole {
  template <class proxy_base>
  class ProxyServer : public proxy_base {
    // etc...

Of course, most C++ programmers, not being blessed by duck-typing (outside of templates), would probably go and use an abstract base class or something instead. pah!

said on 04 Oct 2005 at 17:34

(new Picasso Identicon™

Wow! I am awestruck. I really don’t know what to say. I need to be alone for a while to ponder the consequences.

said on 05 Oct 2005 at 02:03

It does remind me of C+ templates somewhat, but during runtime instead of compile-time, which is when all the fun happens anyway. But don’t discount C+ templates… they’re an awesomely powerful tool that lets the language do all sorts of crazy things, making it at least possible to do all those things that are so easy in ruby.

said on 05 Oct 2005 at 23:20

Hey, I think we’re onto some new flavor of dependency injection. Perhaps the most natural form of DI for ruby yet. And possibly the most powerful. /me spins his wheels…

Comments are closed for this entry.