Adding a directory to the load path in Rails?

Viewed 62400

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.

9 Answers

For older versions of Rails:

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

config.load_paths << "#{RAILS_ROOT}/app/widgets"

--

For Rails 3, see answers bellow

In config/application.rb add config.autoload_paths << "#{config.root}/models/widgets".

File should look like this:

module MyApp
  class Application < Rails::Application
    config.autoload_paths << "#{config.root}/models/widgets"
  end
end

I know this works for Rails 4 and 5. Probably others as well.

If you want to add multiple directories:

config.autoload_paths += Dir[Rails.root / "components/*/app/public"]

(this is an example for packwerk autoload)

Related