Hi --

On Mon, 23 Sep 2002, Tom Sawyer wrote:

> interesting david. just skimmed it over. perhaps it's merely that i just
> woke, but i suspect it's b/c your a ruby programming god :)

No, I think it's because you just woke :-)  Just wait til the
weekend's over and the one-line drop-in replacements and
methodological critiques start showing up -- you'll see :-)

> i will have to read it over again, i haven't fully grasped your example.
> what would be nice though is the contrasting "clunky" example to which
> you refer, as a source of comparison.

(Code is somewhat schematic in what follows, but should give the
idea.)

The thing I was originally doing was something like this:

  # db is the database object; db.fields are the field names
  lines.each do |line|
    r = Row.new(line)
    db.insert(r)
    r.fields = db.fields  # mirror the fields in each row
  end

which I didn't like.  For one thing, the user can set the database
fields, so I had to do something like this:

  def fields=(string)
    @fields = string.split
    each {|key,row| row.fields = @fields}
  end

to keep the db fields and each row's fields in sync.

OK, so then I thought, if the rows just know which database they
belonged to, they wouldn't have to carry their own fields around with
them.  They could get at the fields through the database object.

That led to:

  class Row
    def initialize(db, args)
    ...
    end
  end

and this:

  r = Row.new(self,args)

so now a row could do:

  db.fields     # fields being an attr_reader of the database object

But I really didn't like the passing self thing.

At that point, the question was: where else can the database object be
available?  It occurred to me that it could be known to the *class* of
the rows.  But that class was already written... so then it became a
matter of rewriting it dynamically.

So now, when a new database is created, a new Row class is also
created.  That class lives in the virtual class of the database
object.  It has a @db variable, which hold a reference to the database
object.  Schematically:

      db object  <<<<<<<<<<<<<<<<<<
                                   ^
      class << db object           ^
                                   ^
        class Row                  ^
                                   ^
    >>>>> @db >>>>>>>>>>>>>>>>>>>>>
   ^
   ^      row object
   ^
   ^<<<<<<< type.db


So every Database object has a custom-made Database::Row class
available to it, and that class knows how to get at the database
object.


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