From: Wyss Clemens Date: 2002-02-13T23:05:51+09:00 Subject: RE: reducing redundancies Below is a very rudimentary approach. Hope this suffices to get the idea. class Module def persistentMembers(*members) memebers.each { |member| createGetter(member) createSetter(member) } createInitialize(*members) end def createGetter(memberName) eval("def #{memberName};;end") end ... end class SomeStuff persistentMembers(:foo, :bar, :baz) end Instead of making "persistentMemeber" a Module(/Class) method you could create a mixin module for persistency. Might be even cleaner! Clemens > -----Original Message----- > From: Martin Maciaszek [mailto:mmaciaszek@gmx.net] > Sent: Mittwoch, 13. Februar 2002 14:14 > To: ruby-talk@ruby-lang.org > Subject: reducing redundancies > > > For my project I created some objects that store all data in a > database. All accessors get/set theirs values from/to the > database. I finally ended up with something like this: > > class Somestuff > @@ATTRIBUTES=%w{ foo bar baz } > def initialize(foo, bar, baz) > # do some database magic > @@dbh.do("insert into sometable ("+ @@ATTRIBUTES.join(", ")+ > " ) values (" + @@ATTRIBUTES.collect { |x| "'" + eval( x ) + > "'"}.join(", ") +");" > @id=some id referencing the row created > end > def foo > self.genericReadAccessor "foo" > end > # similar accessors for bar and baz > def foo=(anotherFoo) > self.genericWriteAccessor "foo", anotherFoo > end > # once again similar accessors for bar and baz > def genericReadAccessor(anAttribute) > @@dbh.select_one("select #{anAttribute} from sometable"+ > "where id=#{@id};" )[0] > end > def genericWriteAccessor(anAttribute, aValue) > @@dbh.do("update sometable set set"+ > "#{anAttribute}='#{aValue}' where id=#{@id};" ) > end > end > > What's the point of the lengthy example you ask? Count how often > I had to write "foo" (or "bar" or "baz"). This is unneccesary > redundancy. What happens when sometime in the future "foo" gets > renamed to "qux"? Who's the poor bastard who has to change all > occurences? (probably me with some help of sed, but that's not > the point) > > Is there some way to reduce those redundancies? Ideally I would > just add an new element to the @@ATTRIBUTES and everything would > be fine. > > Any suggestions? > > Cheers > Martin >