Ruby: Checking if a class is a descendant of another class

Posted . Visible to the public.

If you want to find out whether a Class Show archive.org snapshot object is directly inheriting from another class, use superclass:

ActiveRecord::RecordNotFound.super_class == ActiveRecord::ActiveRecordError # => true

To check if another class is an ancestor (not necessarily the direct superclass, but e.g. the superclass of the superclass):

ActiveRecord::RecordNotFound.ancestors.include?(StandardError) # => true

Note that ancestors also includes the receiving class itself as well as any included modules (which is quite practical for most purposes).

If you would like to check if an instance is of a class inheriting from a given class (directly or inheriting), use is_a?:

error = ActiveRecord::RecordNotFound.new
error.is_a?(StandardError) # => true
error.class.ancestors.include?(StandardError) # => true, and another way to write the line above
Henning Koch
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2010-12-08 08:29)