From: "jan aerts (RI)" Date: 2006-11-14T00:40:07+09:00 Subject: Re: classes within classes > -----Original Message----- > From: Jan Svitok [mailto:jan.svitok@gmail.com] > Sent: 13 November 2006 15:03 > To: ruby-talk ML > Subject: Re: classes within classes > > > > > +----------------------------picture-+ > > | +----------------------track1----+ | > > | | | | > > | | x x | | > > | | x x | | > > | | | | > > | | | | > > | +--------------------------------+ | > > | | > > | +----------------------track2----+ | > > | | | | > > | | xx | | > > | +--------------------------------+ | > > +------------------------------------+ > > > > > > > > More elaborately (showing some of the key features) CODE SNIPPET> > > class Picture > > def initialize(width) > > @width = width > > @tracks = Array.new > > end > > attr_accessor :width, :tracks > > > > def add_track(name) > > @tracks.push(Picture::Track.new(name) > > return @tracks[-1] > > end > > > > class Track > > # DO NOT CALL INITIALIZE METHOD DIRECTLY: use Picture#add_track > > def initialize(name) > > @name = name > > end > > attr_accessor :name > > > > def to_svg > > # I NEED THE WIDTH OF THE PICTURE HERE > > return > > some_xml_that_includes_the_width_which_was_defined_in_Picture > > end > > > > class Feature > > ... > > end > > end > > end > > > > > > > > p = Picture.new(800) # Creates a new picture of 800pt width. > > p.add_track('first_track') > > p.add_track('second_track') > > > > > > In the end, the question is: should I make Picture#width a global > > variable, should I add width as an argument to > > Picture::Track#initialize, or is there a more elegant solution? (I > > hope it's the last one...) > > > > Any help would be very much appreciated, jan. > > Hi, > > two ideas: > 1. pass the picture (it)self to the Track constructor and > then query whatever you need 2. have all the svg generating > stuff in another class that will be given the Picture object, > and will iterate through it, creating the xml along the way > (ERB template comes to my mind...) > > Jan > > Thanks for your swift reply, Jan. I did look briefly at these two options, but didn't go for them previously. However, passing the Picture object itself _might_ actually be the best solution. I suppose the code would then look something like: class Picture def add_track(self, name) @tracks.push(Picture::Track.new(self, name)) end class Track def initialize(picture, name) width = picture.width name = name end end end I'll probably go for this one... jan.