Re: What do you do when you need to attach data to an object instance?



On Fri, Apr 15, 2011 at 8:35 AM, Aaron D. Gifford <astounding@xxxxxxxxx> wrote:
Thanks 7stud for the food for thought.  And thanks again, Kevin, for
pointing me to some much easier ways to do what I want.

I'd still like to muse a bit about the wisdom of doing this. The main
problem that can arise from the approach to modify an existing class
or instance belonging to another component is a possible name clash.
Even if you know you are safe with the current version, it may happen
that an updated version later will introduce the exact attribute that
you are adding on the fly now which will likely have bad effects.

I do not know the specifics of your use case but of course using
delegation does not have this name clash issue. Your solution might
be as easy as

SSLContext = Struct.new :key, :user_id

You could also add more functionality to this class but as said, that
totally depends on your use case. I tend to favor composition over
inheritance (or modification) nowadays since it is often more modular.
Granted, in some places you need more boilerplate code (e.g. reading
an attribute before invoking the method that you really want) but you
do not end stuck with tightly coupled (e.g. via inheritance) classes
that you cannot easily untangle.

Kind regards

robert

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

.