Is there a way to get the list of all defined classes. I'm looking for a code like this:
Class.instances.each do |klass|
puts klass.name
end
If there is no way to do this. It is possible to define a class A such that its descendants are registered in it? For example in this way:
class A
...
end
class B < A
end
class C < B
end
A.descendants # => [B, C]
Inspect the __module__ attribute of the class to find out which module it was defined in. A list comprehension along the lines of [m for m in clsmembers if m [1].__module__ == 'mymodule'] should do the trick. You could also supply a lambda function as the predicate to the inspect.getmembers () call, as shown in the question you referred to.
This function considers only classes and subclasses. Not subsubclasses. In fact I have code that provides an abstract class and then classes using this abstract class. Further I have subclasses to my concrete classes - which is why my subclasses are not listed within the returned array.
Often, it is very convenient to list all the methods of a class directly, so that we can perform some pre-processing based on certain methods. Let’s get started! We’ll show you some ways to make this happen, and you can use any one of the below methods.
Method 2: Another way of finding a list of attributes is by using the module inspect. This module provides a method called getmemebers () that returns a list of class attributes and methods. Method 3: To find attributes we can also use magic method __dict__. This method only returns instance attributes. Attention geek!
The ObjectSpace can help you get all instances of a class. This will thus return all defined classes
ObjectSpace.each_object(Class)
p ObjectSpace.each_object(Class){|ob| p ob}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With