3

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!

  • Just curious why you want to do this?... is this purely academic? or are you hoping to pre-cache items? – scunliffe Jul 13 '12 at 12:23
  • No, I am doing this because I won't need to go back to the code to add the class in the predefined array. My belief that it will lower the workload as same as its simpleness to just drop the file with the class into a directory and let the script do the hard part. – user1207719 Jul 13 '12 at 13:55

2 Answers2

7

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)
gmalette
  • 2,439
  • 17
  • 26
0

Assuming that they all share the same name as their containing .rb file and take no arguments to initialize...

#initialize array of objects
objects = []

#list ruby files in directory
classes = Dir.glob( "*.rb" )

#make method to easily remove file extension
def cleanse( fileName )
    return fileName.gsub( ".rb", "" )
end

classes.each do |file|
    #require the new class
    require fileName

    #add it to our array
    objects[objects.length] = eval( cleanse(file) + ".new()" )
end
Mark
  • 694
  • 5
  • 15
  • Your answer contains code that is not typical in Ruby. The snake case is usually preferred and thus `fileName` should be `file_name`. `objects[object.length] = eval...` looks like PHP and would be a lot nicer if it was `objects << eval...` – gmalette Jul 13 '12 at 12:39
  • @gmalette Ah, thanks for that. The strange thing is that I only recently started developing in PHP, I've been working in Ruby for much longer. – Mark Jul 13 '12 at 12:57