您好,我一直在寻找解决此问题的方法。使用 Rails 2.3.5
我有一个包含几个子类的父类,为了没有一个 1500 行长的文件,我将子类保存在 app/models 目录的子目录中。
直到最近,当我查看这篇文章时:这里
我什至无法加载子类
现在我想使用 self.inherited 类方法访问每个孩子,如下所示:
class Project < ActiveRecord::Base
CHILDREN = []
def self.inherited(child)
super
CHILDREN << child
puts "CHILDREN.inspect: #{CHILDREN.inspect}"
end
def self.valid_child_types
CHILDREN.collect{ |child| child.project_type}
end
end
暂时,我放了一些调试语句来更好地了解事物是如何加载的。我启动了控制台并注意到了这种行为:
>> Project
require_or_load /Users/frankdrebin/Sites/cerp/app/models/project.rb
loading /Users/frankdrebin/Sites/cerp/app/models/project
require_or_load /Users/frankdrebin/Sites/cerp/app/models/status.rb
loading /Users/frankdrebin/Sites/cerp/app/models/status
=> Project(id: integer, url: string, deadline: date, state: string, type: string, priority: integer, status_id: integer)
>> Project::CHILDREN
=> []
>> ArticleProject
require_or_load /Users/frankdrebin/Sites/cerp/app/models/projects/article_project.rb
loading /Users/frankdrebin/Sites/cerp/app/models/projects/article_project
CHILDREN.inspect: [ArticleProject(id: integer, url: string, deadline: date, state: string, type: string, priority: integer, status_id: integer)]
require_or_load /Users/frankdrebin/Sites/cerp/vendor/gems/state_machine- 0.7.3/lib/state_machine.rb
loading /Users/frankdrebin/Sites/cerp/vendor/gems/state_machine-0.7.3/lib/state_machine
=> ArticleProject(id: integer, url: string, deadline: date, state: string, type: string, priority: integer, status_id: integer)
>> Project::CHILDREN
=> [ArticleProject(id: integer, url: string, deadline: date, state: string, type: string, priority: integer, status_id: integer)]
>>
我确信对此没有那么优雅的解决方案,例如将子类全部放回一个巨大的文件中,但如果可能的话,我想避免这种情况。
谢谢