views:

1043

answers:

5

Since the latest Rails 3 release is not auto-loading modules and classes from lib anymore, what would be the best way to load them?

From github:

A few changes were done in this commit:

Do not autoload code in *lib* for applications (now you need to explicitly 
require them). This makes an application behave closer to an engine 
(code in lib is still autoloaded for plugins);
+4  A: 

You have a setting in application.rb in which you can specify dirs that contain files you want autoloaded.

From application.rb:

# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
Slobodan Kovacevic
A: 

If only certain files need access to the modules in lib, just add a require statement to the files that need it. For example, if one model needs to access one module, add:

require 'mymodule'

at the top of the model.rb file.

MikeF
You shouldn't use `require` within a rails app, because it prevents `ActiveSupport::Dependencies` from [un]loading that code properly. Instead you should use `config.autoload_paths` like the answer above, and then include/extend as required.
ben_h
A: 

So what's the point in removing autoloading the lib directory when you have to add it to autoload_paths to be able to use "include ModuleName" then?

Cojones
A: 

I had the same problem. Here is how I solved it. The solution loads the lib directory and all the subdirectories (not only the direct). Of course you can use this for all directories.

Hope this helps.

hjuskewycz
A: 

config.autoload_paths += Dir["#{config.root}/lib/**/"] # include all subdirectories

http://www.hemju.com/2010/09/22/rails-3-quicktip-autoload-lib-directory-including-all-subdirectories/comment-page-1/#comment-274

thankful