What is the <appname> .rb file in / lib commonly used for a Ruby project?

In connection with this question: The ideal structure of the ruby ​​project I noticed that appname.rb is in lib and is the top level.

I read some Rake source code on Github and I noticed that their project structure is almost the same. They have a top-level rake.rb file in / lib, but I'm not sure what it is for.

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

So my question is: what exactly is this thing commonly used 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 how many Ruby-foo right now .;)

Thanks.

+6
ruby structure
source share
2 answers

Usually (and, of course, in the rake example), the appname.rb file is a shortcut that requires a large number of other files. If you look at this file in the Rake project on GitHub, most of its actions require files in the lib/rake directory and include modules if necessary. This file is what you require 'rake' without knowing what to do with the rake of individual files.

+5
source share

Based on Emily will answer :

Some projects run autoload instead of require in this file. The latter will actually load all the classes, while the former will simply tell the class loading system how to find them if you reference them without the require statement.

So the template will look like this:

 # 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 
+4
source share

All Articles