Rails module / folder naming convention

I had a problem with the module name and 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 I try to access the class, I get an uninitialized persistent error. However, if I change the module name to REST and the folder for / rest, I will not get an error.

I assume the problem is with the folder naming, and I tried all different combos / rest _v_2, / rest_v2, / restv_2, etc.

Any suggestions?

+6
source share
2 answers

Rails uses the "underscore" method for the name of a module or class to try to figure out which file to load when it encounters a constant that it does not yet know. When you start your module using this method, it does not seem to give the most intuitive result:

 irb(main):001:0> "RESTv2".underscore => "res_tv2" 

I'm not sure why underlining makes this choice, but I'm sure that renaming your dir module to the above will fix your problem (although I think I'd rather just rename it to "RestV2" or "RESTV2" so that the directory name is robust meaning).

+7
source

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

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

Then you can autoload these files.

Also, your likely file name should be app / model / api / res_tv2 / user.rb since Rails uses String.underscore to determine the file name. I would just call it API :: V2 :: User to avoid headaches if you have no more than one type of API.

+5
source

Source: https://habr.com/ru/post/947478/


All Articles