From: Robert Klemme Date: 2004-10-02T06:55:00+09:00 Subject: Re: Can you rewrite this in a better way? "Bob Sidebotham" schrieb im Newsbeitrag news:yRh7d.561483$M95.370027@pd7tw1no... > Bob Sidebotham wrote: >> I would like to define a method that can be used to compactly define some >> items of interest (here called "fields") for subclasses. It's used like >> this: > > Thanks for all the responses. I especially liked: > > class A > def self.fields(*f); @fields||=f; end > def fields; self.class.fields; end > end > > and > > class A > def self.fields(*fields) > define_method(:fields) { fields } > end > end > > The first solution is very clever, but perhaps a little obfuscated. The > second is quite direct--I didn't know about define_method. I hope this > bleeding edge stuff made it into the new pickaxe book. > > Thanks again, > Bob One thing I find irritating about your approach: you define fields on class level but query them on instance level. As long as "fields" is just a list of symbols I'd prefer to deal with them solely on class level. Because that's where it belongs. If OTOH you want this mechanism to do something like attr_accessor (i.e. define something that affects instances' state) then you will access them on instance level but the query ("which fields are there?") still belongs to the class IMHO. Note also that you may want to freeze your fields array especially when accessing it via instances because clients still can modify the array arbitrarily. Kind regards robert