Brian
Brian

Reputation: 2619

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

Upvotes: 19

Views: 3972

Answers (4)

Marc-André Lafortune
Marc-André Lafortune

Reputation: 79562

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).

Upvotes: 30

DigitalRoss
DigitalRoss

Reputation: 146043

Admin.ancestors.include? ActiveRecord::Base

Hmm. Well, this works, but we've just learned a nicer way. It seems that Ruby's Module class defines an operator < for this purpose, and since class Class derives from Module, that means < will directly test for derived classes.

Upvotes: 4

Julian Maicher
Julian Maicher

Reputation: 1793

It's pretty simple:

Admin < ActiveRecord::Base
=> true

Upvotes: 10

Jakub Hampl
Jakub Hampl

Reputation: 40533

Admin.ancestors.includes? ActiveRecord::Base

For direct ancestry you could also use

Admin.superclass == ActiveRecord::Base

Upvotes: 3

Related Questions