4

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?

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
dev_054
  • 3,448
  • 8
  • 29
  • 56

1 Answers1

10

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

widjajayd
  • 6,090
  • 4
  • 30
  • 41
  • Thanks. That's what exactly what I want :) Btw, can you tell me why `Object.const_defined?` is returning me errors instead of simply `true/false`? – dev_054 Jul 18 '17 at 02:34
  • this link can explain better for your question .const_defined? https://stackoverflow.com/a/5758492/938947 – widjajayd Jul 18 '17 at 02:54