autovivify_extension.rb 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # rubocop:disable all
  2. class YARD::CustomExtensions
  3. # Automatically create modules for every parent namespace for the given name.
  4. #
  5. # For exampe, if `name` is `Foo::Bar::Baz`, code objects for `Foo` and `Foo::Bar` will be created
  6. # and added to YARD's registry before continuing to process `Foo::Bar::Baz` as normal.
  7. # This is a copy-paste from the following Github comment
  8. # Full credit goes to @jeraki.
  9. # https://github.com/lsegal/yard/issues/1002#issuecomment-1201852997
  10. def self.autovivify_parents(name)
  11. parts = []
  12. while name =~ /(?:::)([^:]+)$/
  13. parts.push($1)
  14. name = $`
  15. end
  16. return if parts.empty?
  17. ns = :root
  18. n = name
  19. loop do
  20. ns = YARD::CodeObjects::ModuleObject.new(ns, name)
  21. ns.add_file("(autovivifed)")
  22. break if parts.empty?
  23. name = parts.pop
  24. end
  25. end
  26. end
  27. class YARD::Handlers::Ruby::ModuleHandler
  28. def process
  29. modname = statement[0].source
  30. YARD::CustomExtensions.autovivify_parents(modname)
  31. super
  32. end
  33. end
  34. class YARD::Handlers::Ruby::ClassHandler
  35. def process
  36. classname = statement[0].source.gsub(/\s/, '')
  37. YARD::CustomExtensions.autovivify_parents(classname)
  38. super
  39. end
  40. end
  41. # rubocop:enable all