扶手:优雅的方式来构建模型到子文​​件夹,而无需创建子模块扶手、模块、模型、优雅

2023-09-08 15:44:45 作者:人間鴻客

我有许多车型在我的应用程序/模型文件夹中。我想清理这个文件夹了一点点。此举属于彼此的子型号。的问题是,按照惯例模型类命名空间成根据模块。

例如。

应用程序/模型/博客/ post.rb 应用程序/模型/博客/ comment.rb 应用程序/模型/ user.rb

这样:

应用程序/模型/博客/ post.rb

 类岗位< ActiveRecord的
结束
 

而不是

 类博客::邮报< ActiveRecord的
结束
 

解决方案

下面是我用Rails的3:

  config.autoload_paths + = DIR [Rails.root.join(应用程序,模型,{} **')]
 

此配置告诉Rails扫描所有的应用程序/模型的子文件夹递归和加载所有发现的模型。没有命名空间必需的。

I have numerous models in my app/models folder. I'd like to clean this folder up a little bit. Move models that belong to each other in subfolders. The problem is that by convention the model class is namespaced into an according module.

E.g.

app/models/blog/post.rb app/models/blog/comment.rb app/models/user.rb

so that:

app/models/blog/post.rb

class Post < ActiveRecord
end

and not

class Blog::Post < ActiveRecord
end

解决方案

Here is what I used for Rails 3:

config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')]

This configuration tells Rails to scan all the app/models subfolders recursively and load all found models. No namespacing required.