Creating classes only when needed?

Hello,

I am fairly new to ruby and need some help
I am structuring my code using classes.
The application I work on requires input data. This data may require all
or
some of the classes I create. Instead of having a section in the main
code
creating all classes I would like to create only those classes that I
need
while reading the data. However I do not know how to do that. Below is
the
outline of my code.

Any suggestions

class ReadFileFactory

handles calling the right class to for reading the data

from database, from CSV-file, etc.

… code goes here …
end

class CSVReadFile( externalClass, nameID )

handles reading data using a csv-file and assigning it to the

appropriate
Hash
… code goes here …
case signal
when nameID
externalClass.getLine(tempStore)
when …
end

class AddSubscriber

handles adding a subscriber

… code goes here …
end

main program

Initialize I don’t like that

class1 = Class1.new;
class2 = Class2.new; #etc
test = ReadFileFactory.start_csv_readfile(“sample.csv”)

test.processingFile( class1 )

I rather would have something like that

ReadFileFactory.start_csv_readfile(“sample.csv”) will return only the
classes I need.

DÅ?a Utorok 07 Február 2006 00:30 Paatsch, Bernd napísal:

Any suggestions
… code goes here …

I rather would have something like that

ReadFileFactory.start_csv_readfile(“sample.csv”) will return only the
classes I need.

Well, your example is fairly generic, so I’ll be guessing what you
really want
to do.

I think you started on the right track with the factory. If I understand
you
right, that one provides an adapter for the way the data is stored. You
could
continue by storing the data type in the adapter, or whatever it
returns, and
then processing it into some sort of facade processing class that will
internally decide what processing is required for what data and hide
this
from the “main” script body.

David V.
Might be horribly, horribly wrong

On 2/6/06, Paatsch, Bernd [email protected] wrote:

Hello,

I am fairly new to ruby and need some help
I am structuring my code using classes.
The application I work on requires input data. This data may require all or
some of the classes I create. Instead of having a section in the main code
creating all classes I would like to create only those classes that I need
while reading the data. However I do not know how to do that.

Class names are constants. To get a reference to a class from a name
(String or Symbol):

klass = Object.const_get(classname)

Here’s an example to get you going:

class Class1
def run
puts “You chose class 1”
end
end

class Class2
def run
puts “You chose class 2”
end
end

this roundabout way of defining the class name is to emphasise

that you can construct the class name dynamically

n = “1”
classname = “Class#{n}”

klass = Object.const_get(classname)
obj = klass.new
obj.run
#=> You chose class 1"

Regards,

Sean