From: Markus Date: 2004-10-01T12:34:04+09:00 Subject: Re: Can you rewrite this in a better way? No idea if it's "better" but here's one I use: class Module # # To automate the reading and writing of objects # def columns @columns ||= [] end private def field(*ids) @columns ||= [] ids.each { |id| id = id.to_s attr_accessor id unless id =~ /\[/ or instances_respond_to? id+'=' @columns << id } end end On Thu, 2004-09-30 at 18:10, 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: > > class B < A > fields :a, :b, :c > end > > class C < A > fields :x, :y > end > > p B.new.fields => [:a, :b, :c] > p C.new.fields => [:x, :y] > > Here are two definitions for class A that support these semantics: > > ---#1------------------------------------------------ > > class A > def self.fields(*fields) > @fields = fields > def fields > self.class.getFields > end > end > > private > def self.getFields > @fields > end > end > > ---#2------------------------------------------------ > > class A > def self.fields(*fields) > eval "def fields > [#{fields.collect{|f| ':' + f.to_s}.join(',')}] > end" > end > end > > ----------------------------------------------------- > > Is there a better way (more efficient, shorter and/or clearer) to do this? > > Thanks! > Bob Sidebotham >