On Thursday 23 April 2009 16:18:57 Damjan R. wrote:
And I want the third class to subclass class A or B dependent on
parameter passed.
On loading the file? That might not be the best way…
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’)
Ok… First of all, that method is too long… you probably don’t want
obj.do_something in there. You probably want it to return obj so you can
do
something with it.
Second: Do A and B have to be classes? Can they be modules instead?
How about Myclass? Can it be a module instead of a class?
Let’s say A and B are modules:
class MyClass < Abstract
…
end
def run_class type
obj = MyClass.new
obj.extend type
obj
end
run_class(A)
run_class(B)
Or, let’s say MyClass is actually MyModule:
class A < Abstract
include MyModule
end
class B < Abstract
include MyModule
end
not sure why you still need this, but here you go:
def run_class type
type.new
end
Or, if you don’t know which classes MyModule might be mixed into, you
could do
something like this:
def run_class type
obj = type.new
obj.extend MyModule
end
Or, you could even do hacks like this:
[A, B].each do |type|
type.send :include, MyModule
end
Which of these routes makes sense depends very much on what you’re
trying to
build. I don’t know what that is. For example, several people have
suggested
using const_get, but I don’t see why you can’t just pass the
module/class
itself as a parameter – they’re objects, too!