Rails 4: autoloading from lib

I'm trying to figure out what's going on with automatic uploads, but I am having a hard time getting it to work without explicitly requiring the file.

Do I need to create a custom config so that Rails 4 can automatically upload files inside a directory lib

?

If I go to rails console

and type $LOAD_PATH

, I can see what's /home/some_user/workspace/rails/myapp/lib

included in the download path. Does this mean that Rails can automatically download the file?

So, as I understand it,
if I were to put the files inside a directory lib/

, and I were using naming conventions, Rails should be able to automatically request the correct file if anywhere in my code I would do something like this:

cats = Cats::SomeCat.new

(provided that exists lib/cats/some_cat.rb

)

and some_cat.rb

contains:

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

      

However Rails will show me an error uninitialized constant CatController::Cats

.

If I add a line require 'cats/some_cat'

everything works. However, in "The Rails 4 Way" I read this:
 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 being forced to use this config.autoload_paths += %W(#{config.root}/lib)

thing?

+3


source to share


2 answers


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

this code to



config / application.rb

+3


source


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

.

As mentioned by Sobin, the best way would be to include config.autoload_paths...

in this file.



You can find out about this in the guide rails

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

0


source







All Articles