On 24.04.2009 05:01, Andrew Timberlake wrote:
> On Fri, Apr 24, 2009 at 12:51 AM, Tim Hunter <TimHunter / nc.rr.com> wrote:
>> Damjan Rems wrote:
>>> I have three classes.
>>> module mymodule
>>>
>>> class Abstract
>>> end
>>>
>>> class A < Abstract
>>> end
>>>
>>> class B  < Abstract
>>> end
>>>
>>> end
>>>
>>> And I want the third class to subclass class A or B dependent on
>>> parameter passed. my_src is also the name of source file:
>>>
>>> This is what I do:
>>>
>>> I create my_src.rb where I write:
>>> class my_src < Abstract
>>> ....
>>> end
>>>
>>> Finally I have a method to load my class and do something with it.
>>> def run_class(filename, parm)
>>>  src = File.read(filename + '.rb')
>>>  src.sub!('Abstract', parm)
>>> # Evaluate is equal to load
>>>  eval src.to_s
>>>  obj = eval( File.basename(filename).capitalize + '.new' )
>>>  obj.do_something
>>> end
>>> run_class('my_src')
>>>
>>> Ruby is wonderful language which allows us to do this. But the
>>> substitution part is kinda ugly to me.
>>>
>>> So is there a better way of doing this?

The question is: of doing what?  You say you want the third class to 
subclass either A or B.  But the code you presented just replaces the 
first occurrence of "Abstract" with something else.  Also, your 
run_class is not called with the second parameter.

If you want to control inheritance from either A or B you can do

class X < condition ? A : B
end

But frankly, this approach seems strange at least.  The question is, why 
do you need make the inheritance structure of your class configurable? 
The suggestion to make A and B mixin modules seems much better to me. 
You can even extend instances of your class with a module on a case by 
case basis.

Can you present a bigger picture so we can understand what motivates 
your approach?

Kind regards

	robert