Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the proper way to check if a constant is defined?

I have a string and I just want to check if it's a "model"... so after searching I found a way:

'any_name'.classify.constantize

But... when it isn't a valid model name, it throws the following error:

NameError (wrong constant name AnyName):

So I tried to do the following:

if Object.const_defined?('AnyName')
  #...
end

# I also tried this:
Object.const_get('AnyName')

But again, both of the options above returns the same error:

NameError (wrong constant name AnyName):

The const_defined wasn't supposed to return only true/false instead of throw an error?

Currently, I have found this ugly workaround:

'any_name'.classify.constantize rescue nil

But AFAIK it isn't considered a good practice (also rubocop is claiming about this).

So, my question is... is there a safe way to do this?

like image 653
dev_054 Avatar asked Jan 29 '23 23:01

dev_054


1 Answers

There is method safe_constantize that can help you, it will return nil in case not defined

"ModelName".classify.safe_constantize

this is link for safe_constantize

like image 104
widjajayd Avatar answered Feb 01 '23 13:02

widjajayd