From: Ara.T.Howard@... Date: 2004-10-01T11:35:01+09:00 Subject: Re: Can you rewrite this in a better way? On Fri, 1 Oct 2004, 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 i don't know if it's any better, but: harp:~ > cat a.rb class A def self.fields(*f); @fields||=f; end def fields; self.class.fields; end end 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] harp:~ > ruby a.rb [:a, :b, :c] [:x, :y] this would be a great place for a mixin: harp:~ > cat a.rb module Fieldable def self.append_features klass class << klass def fields(*f); @fields||=f; end end super end def fields; self.class.fields; end end class B include Fieldable fields :a, :b, :c end class C include Fieldable fields :x, :y end p B.new.fields # => [:a, :b, :c] p C.new.fields # => [:x, :y] harp:~ > ruby a.rb [:a, :b, :c] [:x, :y] it's not shorter - but it frees you from inheritence, which breaks encapsulation. kind regards. -a -- =============================================================================== | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov | PHONE :: 303.497.6469 | A flower falls, even though we love it; | and a weed grows, even though we do not love it. | --Dogen ===============================================================================