Hello –
[Disclaimer: this isn’t intended as a general solution, just something
I’ve been working on.]
A while ago transami brought up the question of an object needing
access to the object that created it, and there was discussion of
techniques including sending self as an argument. I’ve been working
on a case of the underlying problem he was talking about, and I
thought I’d share my (current) solution. Comments welcome.
The big object is a (simple) database image. It creates Row objects
from arguments to an #insert method, and populates itself hash-wise
with the values.
There are also field names. A Row object needs to know its own field
names, so that one can do things like:
r = db[“Black”] # r is a Row object
r[“first_name”] # => David
Originally I had been creating an array of field names for every row,
but that seemed very clunky. Then I got an idea…
When the database object is created, it creates a new class, which
inherits from an existing Row class (DBDBD::Row). That new class has
an instance variable (i.e., its virtual class defines an accessor
method) called @row_class. The new database object assigns itself to
@db in that Row class’s virtual class:
class DBDB
def initialize(…)
…
@row_class =
class << self
class Row < DBDBD::Row
class << self
attr_accessor :db
end
self
end
end
@row_class.db = self
end
…
end
The Row objects already know that they can get their fields by doing:
type.db.fields
So everybody’s happy
The database object does not have to pass
itself as an argument when initializing rows, and the rows don’t have
to carry around a copy of the field names (which perhaps they were
doing only by reference, so it wasn’t a storage issue, but it was
still awkward).
I just thought I’d share this since it reminded me so exactly of the
problems transami and others had been talking about.
David
···
–
David Alan Black | Register for RubyConf 2002!
home: dblack@candle.superlink.net | November 1-3
work: blackdav@shu.edu | Seattle, WA, USA
Web: http://pirate.shu.edu/~blackdav | http://www.rubyconf.com