[英]Organizing models/controllers and classes in rails in subfolders
I am working in a Rails project in which i have used the below names for model/controller and class files 我在一个Rails项目中工作,在该项目中,我使用以下名称作为模型/控制器和类文件
/app/models/friends/friend.rb
/app/controllers/friends/friends_controller.rb
/lib/classes/friends/friend.rb
I tried to add all the models, controllers and class files in autoload path in application.rb. 我尝试将所有模型,控制器和类文件添加到application.rb的自动加载路径中。 But i am facing issues since the class names are same. 但由于类名相同,我遇到了问题。
How should i handle this? 我该如何处理? and organize files in such a way that files are organized with name spaces. 并以使文件带有名称空间的方式组织文件。
Thanks, Balan 谢谢,Balan
A much better approach would be to use Rails Engines & divide your app in isolated modules. 更好的方法是使用Rails Engines并将您的应用程序分成隔离的模块。
rails plugin new friends --full --mountable --dummy-path spec/dummy
the above command will generate a full mountable engine with isolated namespace, meaning that all the controllers and models from this engine will be isolated within the namespace of the engine. 上面的命令将生成一个具有隔离名称空间的完全可安装的引擎,这意味着该引擎的所有控制器和模型都将隔离在该引擎的名称空间内。 For instance, the Post
model later will be called Friends::Post
, and not simply Post
. 例如,以后的Post
模型将被称为Friends::Post
,而不仅仅是Post
。 to mount this app inside your main rails app, you need do two things: 要将这个应用程序安装到您的主要rails应用程序中,您需要做两件事:
Add entry to Gemfile 将条目添加到Gemfile
gem 'friends', path: "/path/to/friends/engine"
And then add route to config/routes.rb 然后将路由添加到config / routes.rb
mount Friends::Engine, at: "/friends"
For more information on this approch, checkout: 有关此方法的更多信息,请结帐:
The class names are same but path's are different, and you don't need to add classes to autoload except /lib/classes/friends/friend.rb
类名相同,但路径不同,除了/lib/classes/friends/friend.rb
外,无需添加类即可自动加载。
Did you tried the following way: 您是否尝试过以下方式:
# app/models/friends/friend.rb
class Friends::Friends
#...
end
# Friends::Friends.new
# app/controllers/friends/friends_controller.rb
class Friends::FriendsController < ApplicationController
#...
end
# lib/classes/friends/friend.rb
module Classes
module Friends
class Friends
#...
end
end
end
# Classes::Friends::Friends.new
To add lib files to autoload add following to your applicaion.rb
要将lib文件添加到自动加载,请在applicaion.rb
添加以下内容
config.autoload_paths += %W(#{config.root}/lib)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.