Kent Dahl <kentda+news / stud.ntnu.no> wrote in message news:<c9n0f1$i61$1 / orkan.itea.ntnu.no>...
> Alex Gutteridge wrote:
> > The problem I have is that sometimes I have extra data associated with
> > the Atom and/or Residue objects. This extra data always comes later
> > (from a different data file) and usually won't be present. when I need
> > to, I'd like to add this data to the (already created data structure)
> > with the minimum amount of work/fuss.
> > 
> > As far as I can see I have the following options:
> > 
> > 1. Modify the Atom and Residue classes to include the extra data, set
> > to nil originally and then filled in when needed. I'd rather not do
> > this because the code is part of a bigger project which I don't have
> > direct control over, and it seems rather inelegant to have these extra
> > fields which hardly ever get used.
> > 
> > 2. Create a new AtomExtra class which inherits from Atom but adds
> > instance variables and accessors for the new data. Then when I read
> > the extra data I transform each Atom object into an AtomExtra object
> > and add the new data. I guess the crux of my question is what's the
> > neatest, Rubyist way of doing this: Is there a smart way of 'morphing'
> > an object into another type of object (Atom to AtomExtra in this case)
> > or do I have to create a new object, copy all the data across and then
> > reattach the new object into the container structure.
> > 
> > Thanks in advance for any advice or help you can give!
> 
> # 3. Create a ExtraAtomFunctionality module that you
> #    extend your Atom objects with dynamically.
> 
> class Atom
>    #...
> end
> 
> module ExtraAtomFunctionality
>    attr_accessor :my_extra_stuff
> end
> 
> a = Atom.new
> # ...then later when you find you need to augment the object...
> a.extend ExtraAtomFunctionality
> a.my_extra_stuff = "Rogue electron"
> 
> # It may eat more memory than your other suggestions,
> # since it would make singleton classes for each
> # augmented Atom instance.

Yes, thanks for your reply, I actually stumbled on this solution
myself just as you posted. It does exactly what I need, but your last
comment worries me slightly. My structures typically contain 1000's of
Atoms so I wonder how much memory this dynamic augmentation magick
will gobble up. Hopefully, in these days of gigabytes of RAM it won't
be a problem, but we'll see...

Alex Gutteridge