On 5/6/06, Eli B. [email protected] wrote:
I have a flat-file full of records. The way records are stored can be
customized via a separate configuration file. I want to have a class
Database which is a container of Record classes. The Record is best
implemented as a Struct, IMHO, and I want to create the class
dynamically after reading the configuration (which says which fields
there are in a Record). I think it would be convenient for a Record to
be a subclass of Database, since there is no point having Records
without a Database.
I think that what you mean by “subclass” is something different than
the traditional meaning of the term.
Subclassing establishes a “is a” relation between the two classes. To
do it in Ruby you’d write:
class Database
#code goes here
end
class Record < Database
#more code goes here
end
I don’t think this is completely correct, however, since a Record is
not a Database. The relationship you want to establish is “contains”:
a Database contains Records. To do this, you’d have to declare a
collection of Records as an attribute of Database, doing something
like this:
class Database
def initialize()
@records = []
end
def add_record(record)
@records << record
end
#et cetera
end
Defining Record within Database, as in your first example, doesn’t
necessarily do any of those things, and is more commonly known as
creating a “nested class”.
If you want to define Record dinamically, you could maybe do something
like this:
class Record
def initialize(*attribs)
@internal_class = Struct.new(*attribs)
@internal_object = @internal_class.new
end
def method_missing(name, *args)
if @internal_object.respond_to? name
@internal_object.send(name, *args)
else super(name, *args)
end
end
def inspect
@internal_object.inspect
end
end
This way, everytime you create a new Record object, you’ll need to
define what attributes it has (and these attributes would probably
come from you configuration files). You can place the code for the
Record class inside the Database class to make it a nested class, and
you can create an attribute for Database that is an Array or Hash of
Records.