gpt4 book ai didi

ruby-on-rails - Rails 4 中的非事件记录模型结构

转载 作者:太空宇宙 更新时间:2023-11-03 18:13:50 26 4
gpt4 key购买 nike

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

class MatchingMethod
attr_accessor :name
end

class LD < MatchingMethod
end

class Soundex < MatchingMethod
end

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

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

对于每个类(class):

class MatchingMethod::LD < MatchingMethod
end

但是,这次MatchingMethod.descendants找不到不再继承类。

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

最佳答案

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

MatchingMethod.descendants
# => []

MatchingMethod::LD
# => MatchingMethod::LD

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

matching_method 目录加载所有类:

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

它不会监控文件更改。您需要在保存更改后手动加载文件。而且它不会删除任何现有的方法/变量。它只会添加新的或更改现有的。

关于ruby-on-rails - Rails 4 中的非事件记录模型结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29415640/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com