From: Jeff Putsch Date: 2001-12-04T07:13:59+09:00 Subject: [ruby-talk:27379] Re: Selecting class based on external information Thanks, Although I didn't mention it, I had ruled out the brute force approach, and was looking for something like the one Dave provided. Thanks Dave. Jeff. On Tue, Dec 04, 2001 at 06:44:01AM +0900, Dave Thomas wrote: > 3. MOre complex, but sexier: > > Have the Host class hierarchy manage itself, and generate the > factory method semi-automatically. For example: > > class Host > ## > # This is a simple factory system that lets us associate fragement > # types (a string) with a subclass of fragment > > TYPE_MAP = {} > > def Host.os_name(name) > TYPE_MAP[os_name] = self > end > > # Here's the factory method > def Host.for(os_name, *args) > klass = TYPE_MAP[0s_name] || raise("Unknown host: #{os_name}") > return klass.new(*args) > end > > # .. rest of class Host > end > > Then, when you define your subclasses, do > > class SunOS < Host > os_name "SunOS" > # ... > end > > class Linus < Host > os_name "Linus" > # ... > end > > To get the right object given an os_name, you jst call > > my_host = Host.for(os_name) Jeff.