From: Martin Maciaszek Date: 2002-02-13T22:14:17+09:00 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