Reputation: 2619
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
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
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
Reputation: 40533
Admin.ancestors.includes? ActiveRecord::Base
For direct ancestry you could also use
Admin.superclass == ActiveRecord::Base
Upvotes: 3