From: Martin Boese Date: 2008-08-27T18:46:08+09:00 Subject: Re: Difficult Inheritance Problem Hi, I am using something like below for my program. I trick is to use methods instead of class variables as they persist through inheritance. Martin class A def self.define_attr_method(name, value=nil) sing = class << self; self; end sing.class_eval "def #{name}; #{value.inspect}; end" end # Sets and/or returns current difference_mapping def self.difference_mapping(value = nil) self.define_attr_method('difmap', value) unless value.nil? self.difmap end end class B < A difference_mapping 'class B' end class C < B end class D < B difference_mapping 'class D' end puts B.difference_mapping puts C.difference_mapping puts D.difference_mapping This will print: class B class B class D On Wednesday 27 August 2008 09:08:43 Toby Clemson wrote: > Hi all, > > I have a problem I can't think of a solution to with regard to > inheritence. > I have an abstract class that others inherit from: > > class DataObject > class << self > attr_accessor :difference_mapping > > ... > end > ... > end > > The descendents of this class each define their own difference > mapping: > > class Page < DataObject > self.difference_mapping = {:blah => :blah} > end > > I would now like to inherit from the Page class but use its > difference_mapping. Obviously this does not work because the > attr_accessor in the DataObject uses a class instance variable that is > unique to each class. I tried using a proper class variable > (@@difference_mapping) but that is the same for all descending > classes. > > Is there a way to define a class level variable that descends down the > inheritance tree unless it is overridden in the same way as this is > possible for methods? I mean I could wrap the data structure in a > method but that does not seem like a very clean solution. > > Thanks in advance, > Toby