Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Module/Folder Naming Convention

I'm having a problem with a module name and the folder structure.

I have a model defined as

module API
  module RESTv2
    class User
    end
  end
end

The folder structure looks like

models/api/restv2/user.rb

When trying to access the class, I get an uninitialized constant error. However, if I change the module name to REST and the folder to /rest, I don't get the error.

I assume the problem has to do with the naming of the folder, and I've tried all different combos of /rest_v_2, /rest_v2, /restv_2, etc.

Any suggestions?

like image 655
KPheasey Avatar asked Jun 17 '13 14:06

KPheasey


2 Answers

Rails uses the 'underscore' method on a module or class name to try and figure out what file to load when it comes across a constant it doesn't know yet. When you run your module through this method, it doesn't seem to give the most intuitive result:

"RESTv2".underscore
# => "res_tv2"

I'm not sure why underscore makes this choice, but I bet renaming your module dir to the above would fix your issue (though I think I'd prefer just renaming it to "RestV2 or RESTV2 so the directory name is sane).

like image 87
Dhruv Avatar answered Sep 23 '22 20:09

Dhruv


You'll need to configure Rails to autoload in the subdirectories of the app/model directory. Put this in your config/application.rb:

config.autoload_paths += Dir["#{config.root}/app/models/**/"]

Then you should be able to autoload those files.

Also, your likely filename will have to be app/model/api/res_tv2/user.rb, as Rails uses String.underscore to determine the filename. I'd just call it API::V2::User to avoid headaches, unless you have more than one type of API.

like image 25
Tim Dorr Avatar answered Sep 25 '22 20:09

Tim Dorr