Ruby loads all classes in a file

I would like to develop a small application that allows the user to automatically add their own classes by placing them in a specific directory (for example, extension / *. Rb).

After starting the application, I want to download all the files and download all the classes contained in this file. Subsequently, I would like to name a specific method.

In pseudo code, it will 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
+3
source share
3 answers

If you want to use metaprogramming, you can find out what classes exist before uploading files, uploading files and looking at which 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 is just that they have classof class.

+7

, , ( ) ( ), . MyClass s my_class.rb

Dir.glob("extensions/*.rb").each{ |file_path|
  file_name = File.basename(file_path, ".rb")
  require file_name
  class_name = file_name.gsub(/^[a-z0-9]|_[a-z0-9]/){ |a| a.upcase }.gsub(/_/,"")
  class_name.constantize.new.run
}

, class.

+2

Check this gem, it automatically finds and loads (only those that you need and only when you need it) classes for your application.

You can also specify it to view and automatically reload modified files.

http://github.com/alexeypetrushin/class_loader

+1
source

All Articles