Rails 4 中的非活动记录模型结构

Non-activerecord models structure in Rails 4

我的尝试看起来像这样,带有继承的非活动记录模型。 app/models/matching_method.rb:

class MatchingMethod
  attr_accessor :name
end

class LD < MatchingMethod
end

class Soundex < MatchingMethod
end

因此,我可以从使用 MatchingMethod.descendants 中获益。 这很好用。所以我尝试将每个 class 移动到它自己的文件夹中。

models/
  - concern/
  + matching_method/
    - ld.rb
    - soundex.rb
  - matching_method.rb

并且对于每个 class:

class MatchingMethod::LD < MatchingMethod
end

不过,这次MatchingMethod.descendants没找到 继承 classes 了。

有什么建议吗?或者我应该重新设计这种方法。谢谢!

Rails 仅在您请求 MatchingMethod::LD 时加载 ld.rb。它通过 const_missing 解析 class。您需要在代码中请求 MatchingMethod::LD 或手动请求文件 matching_method/ld.rb。在加载 class 文件之前,MatchingMethod 对其后代 LD:

一无所知
MatchingMethod.descendants
# => [] 

MatchingMethod::LD        
# => MatchingMethod::LD 

MatchingMethod.descendants
# => [MatchingMethod::LD] 

matching_method 目录加载所有 classes:

Dir['app/models/matching_method/*.rb'].each do |f| 
   require Pathname.new(f).realpath
end

重新加载它们而不重新启动应用程序(如开发环境中的 Rails 加载程序):

Dir['app/models/matching_method/*.rb'].each do |f| 
   load Pathname.new(f).realpath
end

它不会监视文件更改。您需要在保存更改后手动 load 文件。而且它不会删除任何现有的 methods/variables。它只会添加新的或更改现有的。