On Wed, 27 Jul 2005, Joel VanderWerf wrote:

> Ara.T.Howard wrote:
> ...
>>   class JobRunner
>>     class AbstractJobRunner
> ...
>>     end
>>     class FTPJobRunner < AbstractJobRunner
> ...
>>     end
>>     class HTTPJobRunner < AbstractJobRunner
> ...
>>     end
>>     class SCPJobRunner < AbstractJobRunner
> ...
>>     end
>>     class << self
>>       def new job
>>         klass =
>>           case job.input
>>             when %r|^ftp://|
>>               FTPJobRunner
>>             when %r|^scp://|
>>               SCPJobRunner
>>             when %r|^http://|
>>               HTTPJobRunner
>>           end
>>         klass::new job
>>       end
>>     end
>>   end
>
> In this kind of situation, I like to try to refactor so that the
> switching is done in the subclasses rather than a big case (as I'm sure
> you would have done if this had been a real example with a large number
> of cases). That can be done, for example, by:

<snip nice code>

i totally agree - defintely put the pattern in the class since it belongs
there... otth you could abort early quite easily with conflicting/poorly
written patterns (remembering that part of a framework like this would be to
allow others to plugin classes) and this bug would be very hard to find, eg

   client code:

     class FOOJobRunner < AbstractJobRunner
       PAT = %r|foo|
     end
     class BARJobRunner < AbstractJobRunner
       PAT = %r|bar|
     end
     class FOOBARJobRunner < AbstractJobRunner
       PAT = %r|foobar|
     end

now, depending on the order of classes given by proper_subclasses you may or
may not to the right thing so probably you'd need

   class << self
     def new job
       scs = AbstractJobRunner.proper_subclasses
       klass = nil
       scs.each do |sc|
         if sc::PAT === job.input
           raise if klass
           klass = sc
         end
       end
       klass.first::new job
     end
   end

or similar in order to make sure that there is one, and only one, match
amongst subclasses...

cheers.

-a
-- 
===============================================================================
| email :: ara [dot] t [dot] howard [at] noaa [dot] gov
| phone :: 303.497.6469
| My religion is very simple.  My religion is kindness.
| --Tenzin Gyatso
===============================================================================