Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to load Ruby classes into an application?

Tags:

ruby

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?

like image 566
Geekygecko Avatar asked Jan 23 '09 00:01

Geekygecko


2 Answers

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.

like image 200
ucron Avatar answered Oct 19 '22 23:10

ucron


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.

like image 38
jshen Avatar answered Oct 19 '22 23:10

jshen