How to get all class names in a namespace in Ruby?

Viewed 21860

I have a module Foo, that it is the namespace for many classes like Foo::Bar, Foo::Baz and so on.

Is there an way to return all class names namespaced by Foo?

5 Answers

This alternative solution will load and show all classes under Foo:: including "nested" classes, e.g. Foo::Bar::Bar.

Dir["#{File.dirname(__FILE__)}/lib/foo/**/*.rb"].each { |file| load file }
ObjectSpace.each_object(Class).select { |c| c.to_s.start_with? "Foo::" }

Note: **/*.rb recursively globs.

If you want to include the Foo class itself, you could change your select to e.g. { |c| c.to_s =~ /^Foo\b/ }

Related