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
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
.
well with that would work quite simple with the assumption that you have one class per file and the class name (in camel-case) matches the file name (in underscore), e.g. MyClass s in the file 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
}
if you need multiple classes per file, then you have to parse the file and search for the word after the class keyword.
Check out this gem, it automatically finds and loads (only those You needed and only when You need it) classes for Your app.
You can also specify it it to watch and automatically reloads changed files.
http://github.com/alexeypetrushin/class_loader
精彩评论