Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine if a class A inherits from class B without instantiating an A object in Ruby?

Suppose I want to determine if Admin inherits from ActiveRecord::Base. One way is to do this is Admin.new.kind_of? ActiveRecord::Base, but that instantiates an unused Admin object.

Is there an easy way of doing this without creating an Admin object?

Thanks

like image 874
Brian Avatar asked Mar 06 '11 18:03

Brian


People also ask

How does inheritance work in Ruby?

In Ruby, single class inheritance is supported, which means that one class can inherit from the other class, but it can't inherit from two super classes. In order to achieve multiple inheritance, Ruby provides something called mixins that one can make use of.

Why Multiple inheritance is not supported in Ruby?

Example# Multiple inheritance is a feature that allows one class to inherit from multiple classes(i.e., more than one parent). Ruby does not support multiple inheritance. It only supports single-inheritance (i.e. class can have only one parent), but you can use composition to build more complex classes using Modules.

What is super class in Ruby?

Ruby uses the super keyword to call the superclass implementation of the current method. Within the body of a method, calls to super acts just like a call to that original method. The search for a method body starts in the superclass of the object that was found to contain the original method.

What is a subclass Ruby?

Inheritance is when a class inherits behavior from another class. The class that is inheriting behavior is called the subclass and the class it inherits from is called the superclass.


1 Answers

Sure, just compare the two classes:

if Admin < ActiveRecord::Base
  # ...
end

It is interesting to note that while Module#< will return true if Admin inherits from AR::Base, it will return false or nil if that's not the case. false means that it is the otherway around, while nil is for unrelated classes (e.g. String < Range returns nil).

like image 55
Marc-André Lafortune Avatar answered Oct 01 '22 12:10

Marc-André Lafortune