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? >> >> >> >> by >> TheR > > I'm not sure if this is what you're looking for, but...keep in mind that > the class name ("Abstract") is just a constant that contains the class > object. You can assign that class object to a variable and use the variable > in place of the actual class name when you're defining the subclass. So you > could have > > class A < Abstract > end > > class B < Abstract > end > > if use_A then > sup = A > else > sup = B > end > > class C < sup > end > > Furthermore, you can create a new class with Class.new and specify the > superclass as the argument to new. Then you can create new objects of the > class by sending the new method to the class object. > > my_cls = Class.new(sup) > my_obj = my_cls.__send__(:new) > > -- > RMagick: http://rmagick.rubyforge.org/ > > def run_class(param) Class.new(param) do def test 'Hello World' end end.new #<- Note I've got .new in here end c = run_class(A) c.is_a?(A) #=> true c.test #=> Hello World Andrew Timberlake http://ramblingsonrails.com http://www.linkedin.com/in/andrewtimberlake "I have never let my schooling interfere with my education" - Mark Twain