Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ruby provide a method to show the hierarchy calls?

That's all, i want to see what are the clases that inherits a fixed class. There is a method for this in RUBY?

Aptana offers an option that shows this, but is there any method?

Thanks

like image 486
flyer88 Avatar asked Oct 19 '09 18:10

flyer88


People also ask

What is a Ruby method?

A method in Ruby is a set of expressions that returns a value. Within a method, you can organize your code into subroutines which can be easily invoked from other areas of their program. A method name must start a letter or a character with the eight-bit set.

What is method lookup in Ruby?

When you call a method in Ruby, a lot of things happen behind the scenes. The Ruby interpreter has to know where this method is declared to know what behavior it has to interpret. This process is called the method lookup. It goes through the ancestor chain of an object to see where this method is declared.

How do you define a class method in Ruby?

Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition. By default, methods are marked as public which is defined in the class definition.

How do you call a module method in Ruby?

As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.


2 Answers

Are you asking to see all the ancestors of a class, or the descendants? For ancestors, use:

Class.ancestors

There is no comparable method "out of the box" for descendants, however. You can use ObjectSpace, as below, but it's slow and may not be portable across Ruby implementations:

ObjectSpace.each_object(Class) do |klass| 
  p klass if klass < StandardError
end

EDIT:

One can also use the Class#inherited hook to track subclassing. This won't catch any subclasses created before the tracking functionality is defined, however, so it may not fit your use case. If you need to use that information programmatically on classes defined inside your application, however, this may be the way to go.

like image 112
Greg Campbell Avatar answered Oct 20 '22 01:10

Greg Campbell


Module#ancestors

Example:

class Foo
end

class Bar < Foo
end

Bar.ancestors # => [Bar, Foo, Object, Kernel]
like image 33
Avdi Avatar answered Oct 20 '22 01:10

Avdi