Verify if a class exists

B

Bernd

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
 
S

Simen Edvardsen

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

Try a const_get. Like so:

def class_exists?(name)
begin
true if Kernel.const_get(name)
rescue NameError
false
end
end
 
B

Bernd Burnt

Simen said:
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.
 
S

Simen Edvardsen

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.

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,526
Members
44,997
Latest member
mileyka

Latest Threads

Top