From: Christoph Date: 2002-09-23T21:19:51+09:00 Subject: Re: self as method argument revisited dblack wrote .... > 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: While I am still marveling what problem your are trying to solve - I am sort of wandering why you are creating a Row constant in the scope of the meta (virtual) class of every DBDB instance? I doubt hat you woould ever make use of this constant, unless your are planning on peppering every DBDB instance with a barrage of singleton methods. --- class DBDB # The 1.6 object model is inferior def initialize(...) ... @row_class = Class.new (DBDBD::Row) class << @row_class attr_accessor :db end @row_class.db = self end ... end class DBDB # 1.7 version class Row ... @row_class = self class << self attr_accessor :db end end def initialize(...) ... @row_class = Class.new (DBDBD::Row) @row_class.db = self end ... end --- /Christoph