How to create object of class name of which is in text string?

X

xTRiM

I know what this is about Abstract Factory pattern. But in example at
rubygarden we passing a class to factory and it creates an object from
it.
But how can i pass a text string to factory which will create an object
from it?
In later example: i wish to pass string "Foo" or "Bar" not Foo or Bar.


------ From rubygarden library of patterns ------
class Foo; end
class Bar; end

# Here is the use of the Abstract Factory pattern
def create_something( factory )
new_object = factory.new
puts "created a new #{new_object.class} with a factory"
end

# Here we select a factory to use
create_something( Foo )
create_something( Bar )

Running the code above results in the output:
created a Foo with a factory
created a Bar with a factory
 
F

Farrel Lifson

I know what this is about Abstract Factory pattern. But in example at
rubygarden we passing a class to factory and it creates an object from
it.
But how can i pass a text string to factory which will create an object
from it?
In later example: i wish to pass string "Foo" or "Bar" not Foo or Bar.


------ From rubygarden library of patterns ------
class Foo; end
class Bar; end

# Here is the use of the Abstract Factory pattern
def create_something( factory )
new_object = factory.new
puts "created a new #{new_object.class} with a factory"
end

# Here we select a factory to use
create_something( Foo )
create_something( Bar )

Running the code above results in the output:
created a Foo with a factory
created a Bar with a factory

create_something(Kernel.const_get("Foo"))

Farrel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,522
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top