Skip to content

Instantly share code, notes, and snippets.

@narath
Created January 9, 2023 15:43
Show Gist options
  • Save narath/d7e081d7a4a0952ee06ebfa1c529d5b7 to your computer and use it in GitHub Desktop.
Save narath/d7e081d7a4a0952ee06ebfa1c529d5b7 to your computer and use it in GitHub Desktop.
Find all classes in a directory
# in order to support convention over configuration it can be useful to be able to find all the classes in a directory or
# subdirectory. This lets you have easy factories for subclasses in Rails.
# Requires that you are using Zeitwerk naming conventions for files and classes
class YourRootClass
# this does not work with rails because although the paths are autoloaded
# the objects are not in memory (and are only in memory when instantiated)
# and self.inherited is only called when the classes are put in memory
# note: this likely happens in production but not in development
# def self.inherited(klass)
# @descendants ||= []
# @descendants << klass
# end
# def self.descendants
# @descendants || []
# end
def self.descendants
result = []
model_dir = Rails.root.join("app","models") # wherever you are keeping your root class
processor_files = File.join("type_form","processors","*.rb") # the sub dir
Dir.glob(processor_files, base: model_dir).each do |filename|
filename = filename.gsub(".rb","") #remove the extension
klass = Kernel.const_get(filename.camelize)
result << klass
end
result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment