How do I create automatically a instance of every class in a directory?

前端 未结 2 1522
失恋的感觉
失恋的感觉 2021-01-14 05:45

How do I in ruby create an instance of every class in each file in a directory and providing it as an array?

Thank you in advance!

2条回答
  •  佛祖请我去吃肉
    2021-01-14 06:21

    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)
    

提交回复
热议问题