views:

1972

answers:

4

As of Rails 2.3, what's the right way to add a directory to the load path so that it hooks into Rails' auto-reloading mechanisms?

The specific example I'm thinking of is I have a class that has several sub-classes using STI and I thought it would be a good idea to put them in a sub-directory rather than clutter the top-level. So I would have something like:

#app/models/widget.rb
class Widget < ActiveRecord::Base
   add_to_load_path File.join(File.dirname(__FILE__), "widgets")
end

#app/models/widgets/bar_widget.rb
class BarWidget < Widget
end

#app/models/widgets/foo_widget.rb
class FooWidget < Widget
end

It's the add_to_load_path method that I'm looking for.

+18  A: 

You can do this in your environment.rb config file.

config.load_paths << "#{RAILS_ROOT}/app/widgets"
ryanb
+1  A: 

I found I needed to do this after config block-- no access to config object anymore.

This did the trick

ActiveSupport::Dependencies.load_paths << "#{RAILS_ROOT}/app/widgets"
Lewis Hoffman
+2  A: 

update for Rails 3: you can set this in config/appplication.rb, where this sample is provided by default:

# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{config.root}/extras )
Jacob
A: 

Another update for rails 3 -- activesupport 3.0.0:

Instead of:
ActiveSupport::Dependencies.load_paths << "#{RAILS_ROOT}/app/widgets"

You may need to do this:
ActiveSupport::Dependencies.autoload_paths << "#{RAILS_ROOT}/app/widgets"

gdakram