Named Modules and Rails 3.1.3 autoload_path

I'm having problems with the namespace of the module that I am including in the model.

in / app / models / car.rb

class Car include Search::Car end 

in / lib / search / car.rb

 module Search module Car include ActiveSupport::Concern # methods in here end end 

in / config / application.rb

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

The strange thing is that I do not get any errors directly when starting the server. But if I update the browser after a while, I get this error:

 Expected #{Rails.root}/lib/search/car.rb to define Car 

The nature of the problem indicates that it has something to do with:

/config/environments/development.rb

 config.cache_classes = false 

I also tried putting the search.rb file directly in /lib , where I define Search :

 module Search # Put shared methods here end 

What am I doing wrong?

UPDATE:

Well, it turns out that if I rename Search::Car to Search::CarSearch , it will work. Is it not possible to have modules with the same name in another realm?

+7
source share
1 answer

The error comes from your autoload_paths. config.autoload_paths += Dir["#{config.root}/lib/**/"] will add all directories and their subdirectories to the lib directory. this means that you point the rails to the autoload of the lib / search / directory, so car.rb under this directory should define Car, not Search :: Car. In order for rails to expect lib / search / car.rb to detect Search :: Car, you need to autoload the lib / directory, not lib / search. if you change your autoload to config.autoload_paths += Dir["#{config.root}/lib/"] and put search.rb in lib / with the following code:

 module Search require 'search/car' end 

then the rails will understand and expect that lib / search / car.rb will really define Search :: Car and referring to the Car module / class elsewhere in your code will not refer to this car.rb.

You must delete this line (you should only have autoload for the lib directory): config.autoload_paths += Dir["#{config.root}/lib/search/*"]

+4
source

All Articles