From: Thomas Hurst Date: 2002-05-20T02:45:43+09:00 Subject: Re: Object <-> Relational mapping * Chris Morris (home@clabs.org) wrote: > > db.select_all(long_sql_statement) do |row| > > foo = Foo.new > > foo.a = row['a'] > > foo.b = row['b'].to_i > > foo.c = row['c'].to_f > > #... > > foo.z = row['z'] > > end > Some possible improvements. I'd try to take advantage of .send - so > the loop would be something like: > ... do |row| > # row would need to be a hash > row.each do |colname, colvalue| > foo.send('=' + colname, colvalue) > end > end Unfortunately, my row names do not map directly to object properties, be it because the word I want to use is reserved, or whatever. I could map it I guess, using a hash. > As far as handling row['b'].to_i, etc. -- if it has translate types, > make that transformation in the set accessor method of foo's class. Yes, probably a good general idea. This still doesn't help dealing with relations or make the SQL less painful. Each object is quite likely to have some objects related to it; that requires additional logic watching for id changes and building new objects and maybe adding to them inside the object, ala: last_id = nil db.select_all(bla) do |row| if last_id == row['Id'].to_i bar = FooBar.new # build bar using whatever method foo.collection << bar else records << foo last_id = row['Id'].to_i foo = Foo.new # build foo using whatever method end end Some of this can probably be delegated to superclasses quite easily, but you can see it's still tightly coupling the db schema (need to abstract away the SQL) and the object's makeup in relation to it. [automatically generating src] > You could probably do the same for Ruby classes (including > automatically coding for translations from string to the actual column > datatype). hm, could do.. > I don't know of any generic mapping lib efforts -- but I'd probably be > able to contribute some as needs arise at work. One was with some application server iirc, probably around ruby-talk:25000 -- Thomas 'Freaky' Hurst - freaky@aagh.net - http://www.aagh.net/ - Political history is far too criminal a subject to be a fit thing to teach children. -- W.H. Auden