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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With