以下代码用于确定要执行的自身的子类。它遍历ObjectSpace中的所有内容以查找子类,然后从那里执行正确的子类。在rails中,这不起作用,因为库文件夹中的类不在ObjectSpace中。有什么方法可以在特定文件夹中搜索子类?
def execute
ObjectSpace.each_object(Class).select do |klass|
if (klass < self.class)
klass.designations.each do |designation|
if (designation.downcase.capitalize == @action.downcase.capitalize)
command = klass.new(@sumo_params)
command.execute
end
end
end
end
end
或 - 你会推荐这个问题的优秀解决方案吗?
答案 0 :(得分:0)
我会说为此使用一个模块。因此,这会使您编写如下代码:
LIB / base_methods.rb
module BaseMethods
def self.included(base)
@@classes_including ||= []
@@classes_including << base
end
def do_whatever
@@classes_including.each do |class|
#....
end
end
end
LIB / class_1.rb
class Class1
include BaseMethods
end
答案 1 :(得分:0)
我现在采取了简单的方法(迭代一串字符串值):
def execute
@descendants.each do |descendant|
klass = descendant.downcase.capitalize.constantize
if (klass < self.class)
klass.designations.each do |designation|
if (designation.downcase.capitalize == @action.downcase.capitalize)
command = klass.new(@sumo_params)
command.execute
end
end
end
end
end