19

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

4 Answers 4

30

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

Sign up to request clarification or add additional context in comments.

1 Comment

And if you are looking for the documentation, as it happens, class Class is derived from Module, so: ruby-doc.org/core-1.8.7/classes/Module.html#M000206
10

It's pretty simple:

Admin < ActiveRecord::Base => true 

1 Comment

I like this one, which works because class Class is derived from Module. ruby-doc.org/core-1.8.7/classes/Module.html#M000206
4
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.

Comments

3
Admin.ancestors.includes? ActiveRecord::Base 

For direct ancestry you could also use

Admin.superclass == ActiveRecord::Base 

2 Comments

This will work, but it is not efficient, as it generates an array of all ancestors and then iterates through it looking for ActiveRecord::Base.
Ah yeah just read the source and it creates a new ruby array which is slightly less efficient. Though it has the benefit of slightly easier readability (figuring out "what does this code do?").

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.