3

I'm trying to figure out the auto load thing, but I'm having a hard time making it to work without explicitly requiring the file.

Do I need to make some special configuration so that Rails 4 would be able to auto load files inside lib directory?

If I go to rails console and type $LOAD_PATH I'm able to see that /home/some_user/workspace/rails/myapp/lib is include into load path. This should mean that Rails will be able to auto load correct file?

So as I understand:
if I would place my files inside lib/ directory and I would use the naming conventions, Rails should be able to automatically require the correct file if anywhere in my code I would do something like this:

cats = Cats::SomeCat.new (given that lib/cats/some_cat.rb exists)

and the some_cat.rb contains:

module Cats
    class SomeCat
        def initialize
            @name = "Some cat"
        end
   end
end

However, Rails will show me error uninitialized constant CatController::Cats.

If I add a line require 'cats/some_cat' everything will work. However, in 'The Rails 4 Way' I'm reading that :
The bottom line is that you should rarely need to explicitly load Ruby code in your Rails application (using require) if you follow the naming conventions.

Am I using the wrong naming conventions or am I forced to use that
config.autoload_paths += %W(#{config.root}/lib) thing?

user1463822
  • 837
  • 9
  • 24
  • Did you restart the application? It gets initialized only once when the application gets initialized. – nebula Nov 02 '14 at 16:14
  • 5
    possible duplicate of [Auto-loading lib files in Rails 4](http://stackoverflow.com/questions/19098663/auto-loading-lib-files-in-rails-4) – MZaragoza Nov 02 '14 at 16:38
  • As a side note: Subdirectores of `app/` ( and classes/modules therein) will be loaded, that's what I usually do - creating a subdir e.g. `app/workers`. – lllllll Oct 26 '15 at 17:58

2 Answers2

3

Add config.autoload_paths += %W(#{config.root}/lib) this code in

config/application.rb

Mohit Jain
  • 43,139
  • 57
  • 169
  • 274
Sobin Sunny
  • 1,121
  • 10
  • 14
0

You are correct in saying that you need the configuration in your config/application.rb directory.

As mentioned by Sobin, the best way would to include a config.autoload_paths... in that file.

You can find more about this in the rails guides

http://edgeguides.rubyonrails.org/configuring.html

Diego
  • 594
  • 2
  • 10
  • 29