我如何自动创建一个目录中每一个类的实例? [英] How do I create automatically a instance of every class in a directory?
本文介绍了我如何自动创建一个目录中每一个类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Ruby中我做的每个文件在目录中创建的每一个类的实例,
提供它作为一个数组?
How do I in ruby create an instance of every class in each file in a directory and providing it as an array?
感谢你在前进!
推荐答案
您可以使用的ObjectSpace
来发现新的类,然后实例化它们。
You can use the ObjectSpace
to find the new classes and then instantiate them.
def load_and_instantiate(class_files)
# Find all the classes in ObjectSpace before the requires
before = ObjectSpace.each_object(Class).to_a
# Require all files
class_files.each {|file| require file }
# Find all the classes now
after = ObjectSpace.each_object(Class).to_a
# Map on the difference and instantiate
(after - before).map {|klass| klass.new }
end
# Load them!
files = Dir.glob("path/to/dir/*.rb")
objects = load_and_instantiate(files)
这篇关于我如何自动创建一个目录中每一个类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文