Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get all defined classes? [duplicate]

Tags:

ruby

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] 
like image 275
Daniel Hernández Avatar asked Apr 06 '13 15:04

Daniel Hernández


People also ask

How to find out which module a class is defined in?

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.

Does this function only consider classes and subclasses?

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.

Why list all the methods of a class directly?

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.

How to get a list of attributes of a class?

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!


Video Answer


2 Answers

The ObjectSpace can help you get all instances of a class. This will thus return all defined classes

ObjectSpace.each_object(Class)
like image 70
gmalette Avatar answered Nov 15 '22 09:11

gmalette


p ObjectSpace.each_object(Class){|ob| p ob}
like image 38
Arup Rakshit Avatar answered Nov 15 '22 09:11

Arup Rakshit