From: Tom Sawyer Date: 2002-09-23T03:08:42+09:00 Subject: Re: self as method argument revisited 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 :) 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. very interested in this, thanks, tranasmi On Sat, 2002-09-21 at 21:43, dblack@candle.superlink.net wrote: > 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 > > -- tom sawyer, aka transami transami@transami.net