For Programmers: Free Programming Magazines  


Home > Archive > Ruby > August 2005 > Re: Circular dependecy on classes









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: Circular dependecy on classes
Robert Klemme

2005-08-28, 6:59 pm

2005/8/26, Anatol Pomozov <anatol.pomozov@gmail.com>:
> I have several classes that have circular dependencies on each other.
> See following example.
>=20
> class Solder
> @can_upgrade_to =3D [Knight]
> #or use constant from Knight class
>=20
> def upgrade!(to)
> raise "Unable to upgrade" unless @can_upgrade_to.contain(to)
> end
> end
>=20
> class Knight < Solder
> end
>=20
> I cant use Knight constant (class name) before Solder and can't use
> Solder before Knight.
>=20
> I am just come from Java lang and for Java circular class deps is not
> a problem.
> But ruby is a dynamic language and it creates classes just on script
> executing. (right?)
>=20
> So my questions is: how to solve this problem? What is the best way to
> deal with it.


The easiest soltuion: Reopen class Solder after you defined class
Knight and put all the
code there.

But you can as well use #inherited to track all sub classes of Solder.
Thus making sub class registration automatic. Something along the
lines of (untested):

class Solder
def self.inherited(sub_class)
def sub_class.inherited(cl) superclass.inherited(cl) end
(@sub_classes ||=3D []) << sub_class
end

def upgrade_to?(cl)
raise "error" unless cl.ancestors.include? cl
...
end
end

Btw, did you mean "Soldier"?

Kind regards

robert


Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com