required_sub_paths.rb 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module Mixin
  3. module RequiredSubPaths
  4. def self.included(base)
  5. base_path = ActiveSupport::Dependencies.search_for_file base.name.underscore
  6. backends_path = base_path.delete_suffix File.extname(base_path)
  7. eager_load_recursive(base, backends_path)
  8. end
  9. # Loads a directory recursively. This can be needed when accessing
  10. # modules not directly via .constantize on a known string, but dynamically
  11. # via the inheritance tree, e.g. via .descendants (which assumes they have
  12. # previously been loaded).
  13. def self.eager_load_recursive(base, path)
  14. excluded = ['.', '..']
  15. Dir.entries(path).each do |entry|
  16. next if excluded.include?(entry)
  17. sub_path = File.join(path, entry)
  18. namespace = "#{base}::#{entry.sub(%r{.rb$}, '').camelize}"
  19. if File.directory?(sub_path)
  20. eager_load_recursive(namespace, sub_path)
  21. elsif entry.ends_with?('.rb')
  22. namespace.constantize
  23. end
  24. end
  25. end
  26. end
  27. end