hello
is there a way to get all classes defined within a module ?
something like this:
require "mymodule"
classes = mymodule.classes_within_this_module
markus
hello
is there a way to get all classes defined within a module ?
something like this:
require "mymodule"
classes = mymodule.classes_within_this_module
markus
Markus Jais wrote:
hello
is there a way to get all classes defined within a module ?
something like this:
require “mymodule”
classes = mymodule.classes_within_this_module
^^^^^^^^ what is this?
In ruby, modules and files are different things, though they are often
in a one-to-one correspondence. I’ll assume that you are interested in
modules.
The following will give you all the classes defined in the scope of String.
String.constants.map {|x| String.const_get x}.grep(Class)
But this includes things like Float that are defined in Object. So let’s
define:
class Module
def my_classes
constants.map {|x| const_get x}.grep(Class)
end
end
Then you can do
String.my_classes - String.superclass.my_classes
which will be empty, unless you add a class in String:
class String
class S; end
end
after which the subtraction will return:
[String::S]
One more twist: you may also want to subtract constants that come from a
mixin module.
module Enumerable
class E
end
end
String.my_classes - String.superclass.my_classes
So let’s define:
class Module
def my_own_classes
my_classes - ancestors.map {|a|
(a == self)? : a.my_classes
}.flatten
end
end
String.my_own_classes