From: Ross Bamford Date: 2006-05-06T19:06:32+09:00 Subject: Re: Record good idea? On Sat, 2006-05-06 at 18:08 +0900, Frank Hirsch wrote: > Hija! > > I have made a little record class, because I needed it. > > Maybe anyone finds this useful, or wants to beat me, > because I have overtreaden some unwritten Ruby rule... :-))) > > >---------------- cut here ----------------< > > class Record > =begin > Little record class. > (w) Frank Hirsch 2006 > =end > def method_missing(*a) > if (a.length!=2) > super > elsif (a[0].class!=Symbol) > super > else > name=a[0].id2name > value=a[1] > eval("@"+name+"value",binding) > eval("def "+name+"(v);@"+name+"v;end") > name.chop! > eval("def "+name+";@"+name+";end") > end > end > def initialize > end > end > > >---------------- and here ----------------< > > Okay, what does anybody think? > Useful or heresy or just an old hat? I took the liberty of refactoring your code a bit, mainly to avoid string eval and to ignore non-attribute single-arg methods: class Record def method_missing(sym, *a) if (name = sym.to_s) =~ /[^=]=$/ rdr, ivar, value = name.chop, "@#{rdr}", a.first (class << self; self; end).class_eval do define_method(sym) { |v| instance_variable_set("@#{rdr}",v) } define_method(rdr) { instance_variable_get("@#{rdr}") } end self.send(sym,value) else super end end end But please also check out: http://www.ruby-doc.org/stdlib/libdoc/ostruct/rdoc/ http://www.ruby-doc.org/core/classes/Struct.html -- Ross Bamford - rosco@roscopeco.REMOVE.co.uk