kind_of? and superclass

9 views
Skip to first unread message

onion wushu

unread,
Jun 25, 2010, 8:25:35 AM6/25/10
to rubyonra...@googlegroups.com
Hi :)

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 :)
Have a nice day
--
Posted via http://www.ruby-forum.com/.

Rick DeNatale

unread,
Jun 25, 2010, 8:33:33 PM6/25/10
to rubyonra...@googlegroups.com
On Fri, Jun 25, 2010 at 8:25 AM, onion wushu <li...@ruby-forum.com> wrote:
> Hi :)
>
> 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 ?

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: http://github.com/rubyredrick
Twitter: @RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale

Reply all
Reply to author
Forward
0 new messages