From: Francis Cianfrocca Date: 2007-05-26T20:32:10+09:00 Subject: Re: Forward references? ------=_Part_37304_12108449.1180179129645 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 5/26/07, Peter Seebach wrote: > > I am trying to figure out what the cleanest way is to express a class that > has > subclasses. > > Imagine, if you will: > class Foo > def initialize > @bar = Foo::Bar.new(self) > end > end > > class Foo::Bar > def initialize(foo) > @foo = foo > end > end > > Is that a good rubyish way to do this? If I put Foo::Bar in > its own file, should foo.rb be responsible for requiring it? > What originally got me thinking was that my habit is to put requires, > includes, and such at the top of the file... But then the > declaration "class Foo::Bar" refers to an undefined constant. The fact that "Foo::Bar" is undefined in Foo#initialize doesn't matter to Ruby's parser. The whole notion of "forward references" is really more at home in languages that build symbol-tables at compile time. Ruby just deals with the names themselves. Given that, I'd look at the application semantics for a clue to your question. Foo makes reference to Foo::Bar. If they're that closely related, why would you then not simply include the definition of Bar inside the definition of Foo? Two possible reasons: you want to segregate them textually to make your code easier to read, or you want to support multiple definitions of Bar, to be determined at runtime. In either case, you can place the require statements where it makes the most sense for the user of Foo. You can defend yourself against Bar being required ahead of Foo by coding it like this: class Foo class Bar ... end end ------=_Part_37304_12108449.1180179129645--