From: "David A. Black" Date: 2008-08-27T20:37:48+09:00 Subject: Re: Difficult Inheritance Problem Hi -- On Wed, 27 Aug 2008, 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. The easiest way I can think of is: class Page class << self attr_accessor :difference_mapping end def self.inherited(c) c.difference_mapping = difference_mapping end end Page.difference_mapping = { :blah => :blah } class Next < Page end p Next.difference_mapping # { :blah => :blah } David -- Rails training from David A. Black and Ruby Power and Light: Intro to Ruby on Rails January 12-15 Fort Lauderdale, FL Advancing with Rails January 19-22 Fort Lauderdale, FL See http://www.rubypal.com for details and updates!