Search code examples
rubyclassloader

ruby load all classes in a file


I'd like to develop a little application which lets user automatically add their own classes by placing them in a specific directory (e.g. extension/*.rb).

After starting the application I want to load all the files and load all the classes contained in this file. Afterwards I'd like to call a specific method.

In pseudocode it would look like this:

for each file in extensions/*.rb
 arr = loadclasses(file)
 for each class in arr
  obj = class.new_instance
  obj.run
 end 
end

Solution

  • If you want to use metaprogramming, you could find out what classes existed before you load the files, load the files, and see what new classes have been created.

    existing_classes = ObjectSpace.each_object(Class).to_a
    #load the files
    new_classes = ObjectSpace.each_object(Class).to_a - existing_classes
    non_anonymous_new_classes = new_classes.find_all(&:name)
    objects = non_anonymous_new_classes.map(&:new)
    

    Remember: classes are just objects. It's just that they happen to have a class of Class.