Forum: Ruby Verify if a class exists

02f778a079c8cdda087935377f527f11?d=identicon&s=25 Bernd (Guest)
on 2007-07-04 14:05
Hello everybody,

is there a way to check, if a class exists? I create classes dynamically
and would like to know before, if a class with that name already exists.

Thanks for your help
Bernd
F2d901ea9430646c6dd35a629bb3f119?d=identicon&s=25 Simen Edvardsen (Guest)
on 2007-07-04 14:29
(Received via mailing list)
On 7/4/07, Bernd <burnt99@hotmail.com> wrote:
>
>

Try a const_get. Like so:

def class_exists?(name)
  begin
    true if Kernel.const_get(name)
  rescue NameError
    false
  end
end
59610f5c82493698d8313222ea71bfc1?d=identicon&s=25 Bernd Burnt (burnt)
on 2007-07-04 14:36
Simen Edvardsen wrote:
> On 7/4/07, Bernd <burnt99@hotmail.com> wrote:
>>
>>
>
> Try a const_get. Like so:
>
> def class_exists?(name)
>   begin
>     true if Kernel.const_get(name)
>   rescue NameError
>     false
>   end
> end

Hi,
first of all, thanks for your help, Simen. I think, I even found a
better solution, I assign the name to the class with

Object.const_set class_name, klass

So I can determine, whether the class exists with

Object const_defined? class_name

You are using exception handling (rescue) for a conditional branch,
which I try to avoid whenever possible, to keep my code well structured.
F2d901ea9430646c6dd35a629bb3f119?d=identicon&s=25 Simen Edvardsen (Guest)
on 2007-07-04 14:59
(Received via mailing list)
On 7/4/07, Bernd Burnt <djbearhand@gmx.de> wrote:
> >   rescue NameError
> So I can determine, whether the class exists with
>
> Object const_defined? class_name
>
> You are using exception handling (rescue) for a conditional branch,
> which I try to avoid whenever possible, to keep my code well structured.
>

There is a const_defined? method? Ah, I see it's been some time since
I programmed Ruby. Excuse my ignorant advice, it seems you find a
better solution :)
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.