I am developing a Gem that will allow users to auto-require, instantiate, and register classes in a specific directory. I’m just not sure how to achieve this. This is what I’ve come up with so far…
Dir[Dir.pwd + '/extensions/*.rb'].each do |file|
require file
extension_class = # instantiate the class here
MyApp.extensions << extension_class
end
How can I instantiate the class without knowing what it is called?
It sounds like you are making a system for writing extensions to software. Since the extension classes are probably all similar in some way, such as sharing some common methods, it might make sense to have a base class called
Extensionfrom which all the extension classes inherit.In fact, this is very useful to the stated problem because when a user inherits from your class you can detect it, and add the subclass to a list. Here is some proof of concept code:
If you don’t want to use subclassing for some reason, it is equally easy to make
Extensionbe a module and use theincludedhook instead ofinherited.Personally, I would just remove the call to
.newbecause I don’t see a reason to instantiate the class right away, but that’s up to you. I would just store a list of classes.