Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 851
leifg Avatar asked Nov 07 '25 06:11

leifg


1 Answers

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.

like image 150
Andrew Grimm Avatar answered Nov 08 '25 20:11

Andrew Grimm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!