tags:

views:

79

answers:

2

In reference to this question: http://stackoverflow.com/questions/614309/ideal-ruby-project-structure I noticed that appname.rb is in lib, and is top level.

I was reading through a little of the Rake source code on Github, and I noticed their project structure is pretty much the same. They have a top level 'rake.rb' file in /lib, but I'm not sure what it's there for.

In The Pickaxe (Programming Ruby 1.9), they show an example of structuring a small project, with pretty much the same directory structure above, but there is no mention of the usage of a top level .rb in /lib.

So, my question is: What exactly is this thing typically used for in a Ruby project?

Sorry if this is a stupid question, I'm sure it is, but I'm relatively new to Ruby. I don't know that much Ruby-foo right now. ;)

Thanks.

+3  A: 

Usually (and certainly in the example of rake) the appname.rb file is a shortcut to require a lot of other files. If you take a look at that file in the Rake project on GitHub, most of what it does is require files in the lib/rake directory and include modules as necessary. That file is what lets you require 'rake' without having to know what individual files rake needs.

Emily
Oh, I see! Thanks, Emily.
Rayne
+2  A: 

Building on Emily's answer:

Some projects do an autoload instead of a require in that file. The latter will actually load all of the classes, whereas the former will simply tell the class-loading system how to find them if you reference them without a require statement of your own.

So the pattern would look like:

# in foo_project/lib/foo.rb:
module Foo
  autoload :Bar, 'foo/bar'
  autoload :Baz, 'foo/baz'
end

# in foo_project/lib/foo/bar.rb:
module Foo
  class Bar
  ...
end

# in foo_project/lib/foo/baz.rb:
module Foo
  class Baz
  ...
end

Then, in your project, you can do the following:

require 'foo'
# note: no require 'foo/bar' or 'foo/baz'
my_bar = Foo::Bar.new
James A. Rosen
I've heard of, but never used, autoload. That's neat!
Emily