Kind_of? and superclass

Hi :slight_smile:

In my application, I would like to know if a class is a subclass of
ApplicationController, I mean, if a class is a controller.

I thought about this kind of code:

klass = classname
while klass && klass != ApplicationController
klass = klass.superclass
end

It’s working well but I’m wondering if there is a way to use the ruby
fonction kind_of? to do it well.
Actually, when I want to check if (for example) UsersController is a
controller, I write: UsersController.kind_of?(ApplicationController),
but it doesn’t work at all. Do you have any ideas why ? Or do you know a
better solution to handle it ?

Thanks :slight_smile:
Have a nice day

On Fri, Jun 25, 2010 at 8:25 AM, onion wushu [email protected]
wrote:

end

It’s working well but I’m wondering if there is a way to use the ruby
fonction kind_of? to do it well.
Actually, when I want to check if (for example) UsersController is a
controller, I write: UsersController.kind_of?(ApplicationController),
but it doesn’t work at all. Do you have any ideas why ? Or do you know a
better solution to handle it ?

object.kind_of?(class) tests if object is an instance of class or one
of it’s superclasses, UserController is an instance of it’s metaclass
so it isn’t an instance of ApplicationConrtroller or one of it’s
subclasses.

Use the Module#< method

UsersController < ApplicationController

which returns true if the argument is one of the receivers ancestors,
there is also Module#<= which also returns true if the receiver is
equal to the argument as well.

–
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Github: rubyredrick (Rick DeNatale) · GitHub
Twitter: @RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale