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

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,705
Latest member
Stefkari24

Latest Threads

Top