tags:

views:

2298

answers:

4

Currently I am loading Ruby classes into each class file using the require command, for example:

require File.join(File.dirname(__FILE__), 'observation_worker')
require File.join(File.dirname(__FILE__), 'log_worker')

For each class I am defining the classes it requires. It would be great if I could do this at the entry point to my application.

Is there an easy way to load all the Ruby classes at the start of an application?

+2  A: 

Not sure I fully understand, since you will always have to tell your program what files it needs, but you could do something like:

Dir["#{File.dirname(__FILE__)}/*.rb"]{|f| require(f)}

Which will include all .rb files from the directory of the current file. Although if you ever start using RDoc, it will not be happy with you.

It's generally not a bad thing to list your requires explicitly, it makes it clear to other developers reading your code what is going on.

ozone
A: 

You still need to specify what to load, but you can try autoload.

autoload :Module, "module"

When the constant Module is first used the file "module" will be required automatically.

dylanfm
+2  A: 

If you have a somewhat clear directory structure of where your code goes you could add specific directory paths to the load path like

$LOAD_PATH.unshift( File.join( File.dirname(__FILE__), 'lib' ) )

then in other parts of your code you could require from a relative path like so:

require 'observation_worker'
require 'logger_worker'

or if you have folders within lib you could even do

require 'workers/observation'
require 'workers/logger'

This is probably the cleanest way to handle loading within a library's context in my opinion.

ucron
+1  A: 

Here's an option I like using.

http://github.com/dyoder/autocode/tree/master

From the github doc

  require 'autocode'

  module Application
    include AutoCode
    auto_load true, :directories => [ :configurations, :models, :views, :controllers ]
  end

This will attempt to load code dynamically from the given directories, using the module name to determine which directory to look in. Thus, Application::CustomerModel could load the file models/customer_model.rb.

Also, you can check out the way rails boots.

jshen