required_sub_paths.rb 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. module Mixin
  3. module RequiredSubPaths
  4. def self.included(_base)
  5. path = caller_locations(1..1).first.path
  6. sub_path = File.join(File.dirname(path), File.basename(path, '.rb'))
  7. eager_load_recursive(sub_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(path)
  14. excluded = ['.', '..']
  15. sub_paths = []
  16. Dir.entries(path).each do |entry|
  17. next if excluded.include?(entry)
  18. sub_path = File.join(path, entry)
  19. if File.directory?(sub_path)
  20. sub_paths.push(sub_path)
  21. elsif sub_path =~ %r{\A(.*)\.rb\z}
  22. require_path = $1
  23. require_dependency(require_path)
  24. end
  25. end
  26. sub_paths.each do |sub_path|
  27. eager_load_recursive(sub_path)
  28. end
  29. end
  30. end
  31. end